From 50e5baebe8c1bb5ccbb8e77ae6d848bb01c60fe1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 30 Oct 2026 09:10:05 +1300 Subject: [PATCH 01/34] Retain first-observation delay and bounded observer recovery evidence --- design/project-management/ai-observations.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index a46c26ceab..bc96f693fc 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -700,3 +700,9 @@ Gameplay #3310 Hosted7 finished at 03:51:18 NZDT but its native evidence was rec - Expected pattern: Compare provider finish, controller observation, record and operation-completion timestamps before attributing Hosted latency. Preserve the original attempt and retry/quota state while the owner correction is pending; do not conflate this lag with the separately diagnosed #3310 parser issue or unknown CLI timing. - Outcome: FireController Worker reports the actual cadence correction deployed at `783d5dc1`, with all 30 CI checks passing. Complete ambiguous observations now retain the normal 30-second cadence instead of escalating to five minutes; attribution, reservations and provider cooldowns remain unchanged. Compact output exposes the existing provider-finish and evidence-recorded timestamps. Improved live latency has not yet been separately measured; existing running MCP sessions adopt the additive fields on a normal safe host reconnect. + +- `2026-10-30`: Distinguish first-observation delay from result-delivery delay + - Context: #3331's actual Smoke Gate completed at 07:51:09 NZDT; the sole observer's first retained terminal read was 08:16:37 NZDT, followed promptly by its handoff. + - Observation: The 25-minute 28-second gap preceded first observation; its cause is unknown. This differs from the earlier observed-but-unreported #3327 result. Neither the provider finish time nor an active observer alone proves timely detection, and no FireController latency cause is established. + - Expected pattern: Retain provider-finish, first-observation and owner-handoff times separately. Prioritize the front's substantive run on a bounded per-target observation schedule while independent review waits continue; skip repeated calls to an already known incompatible client endpoint and preserve the one-observer boundary. + - Outcome: Main selected approximately 90-second front checks and five-minute successor checks, with prompt failure/terminal handoffs and the supported bound CLI for incompatible operation reads. Improved detection latency has not yet been separately measured. From c9f8c08470dde7208cca06f885cb148353b47323 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 30 Oct 2026 10:16:24 +1300 Subject: [PATCH 02/34] docs: retain front observation and retarget recovery lessons --- design/project-management/ai-observations.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 882ac559de..396d0ffff5 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -706,3 +706,15 @@ Gameplay #3310 Hosted7 finished at 03:51:18 NZDT but its native evidence was rec - Observation: The 25-minute 28-second gap preceded first observation; its cause is unknown. This differs from the earlier observed-but-unreported #3327 result. Neither the provider finish time nor an active observer alone proves timely detection, and no FireController latency cause is established. - Expected pattern: Retain provider-finish, first-observation and owner-handoff times separately. Prioritize the front's substantive run on a bounded per-target observation schedule while independent review waits continue; skip repeated calls to an already known incompatible client endpoint and preserve the one-observer boundary. - Outcome: Main selected approximately 90-second front checks and five-minute successor checks, with prompt failure/terminal handoffs and the supported bound CLI for incompatible operation reads. Improved detection latency has not yet been separately measured. + +- `2026-10-30`: Keep front merge observation after CI becomes terminal + - Context: #3331 merged at 09:19:31 NZDT while Gameplay continued successor fixes. Main had retired its completed CI observation without retaining front PR merge observation. + - Observation: #3332 remained on the merged parent's feature base; the first retained parent-unavailable probe was 09:35:57, and Main confirmed the merge and retargeted at about 09:41. This delayed front reconciliation. Existing instructions did not change, and no User judgment was needed for the routine transition. + - Expected pattern: Keep compact front PR state/head/base/merge observation in the existing single observer after CI is terminal; continue successor work and promptly reconcile a merged-parent transition. + - Outcome: Main retargeted #3332 to develop and restored that observation scope, reporting the orchestration failure to Overseer. The source tree and unique 47-file patch were unchanged; matching retarget CI remains a separate obligation. + +- `2026-10-30`: Correct retarget event data can still reference a stale test merge + - Context: #3332 moved from merged parent a313 to develop5bae, whose tree is identical and which contains a313 as a merge parent. The PR head remained55e9. + - Observation: The edited event correctly named base5bae/head55e9, but mergea7a99263 retained parents a313/55e9. Runtime image-tag derivation and Preview identifier derivation refused that stale artifact, and native readiness reported ci_merge_base_mismatch. New images and smoke were not run. This differs from the earlier #3310 event whose base field was stale; no new root cause is established. + - Expected pattern: Compare event identity, actual merge parents and stable live base separately, retain the failed runs and obtain the supported current-comparison recovery from the owning CI/tool lane. Old green or a dummy commit does not establish current-base proof. + - Outcome: Exact evidence was reported to Overseer and FireController. A normal ancestry merge of the stable develop base produced `a00d9c0f8928` with a byte-identical source tree; the subsequent retained refresh verified the new test-merge identity. Current CI is separate and still pending. The tool owner installed diagnostic improvement `aeb84eaf`, explaining GitHub regeneration and repository-authorized reconciliation without claiming a controller refresh can regenerate GitHub refs. The original stale-artifact failure and unknown upstream cause remain retained. From e1953c111651d7529c18d3983009147cbce342c6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 30 Oct 2026 10:47:09 +1300 Subject: [PATCH 03/34] Prepare ordinary Account UUID receiving across existing consumers --- .../account-service/api-contracts.md | 10 +- .../account-service/runtime-and-data.md | 4 +- .../logging-admin-service/api-contracts.md | 10 +- .../logging-admin-service/runtime-and-data.md | 1 + .../social-groups-service/api-contracts.md | 8 +- .../social-groups-service/runtime-and-data.md | 1 + design/project-management/ai-observations.md | 6 + .../player-access-and-session.md | 8 + .../controller/AccountController.java | 36 +- .../controller/AccountRequestReaders.java | 10 + .../controller/ProfileController.java | 31 +- .../dto/AuthenticationResult.java | 10 +- .../dto/PlayerBootstrapResult.java | 2 +- .../accountservice/dto/ProfileDto.java | 2 +- .../dto/UpdateProfileRequest.java | 2 +- .../accountservice/mapper/ProfileMapper.java | 6 +- .../service/impl/AccountGrpcService.java | 394 ++++- .../service/impl/AccountServiceImpl.java | 121 +- .../src/main/resources/application-prod.yml | 2 + .../src/main/resources/application.yml | 2 + .../src/main/resources/openapi.yaml | 30 +- .../AccountApplicationIntegrationTest.java | 97 +- .../controller/AccountControllerTest.java | 95 +- .../controller/AuthControllerTest.java | 21 +- .../controller/ProfileControllerTest.java | 171 +- .../PublicBootstrapRoutesProdProfileTest.java | 7 +- .../dto/AuthenticationResultTest.java | 40 + .../AccountRuntimeConsumerAuthWiringTest.java | 406 +++++ .../service/impl/AccountGrpcServiceTest.java | 1413 ++++++++++++++--- .../service/impl/AccountServiceImplTest.java | 422 ++++- .../impl/ScriptEventIngressServiceImpl.java | 15 +- .../ScriptEventIngressServiceImplTest.java | 86 +- .../GameplaySessionAttestationService.java | 20 +- .../common/security/GrpcClientAuth.java | 6 +- .../firemud/common/security/JwtClaims.java | 32 +- .../common/security/SessionClaims.java | 13 +- .../common/security/SessionContext.java | 8 +- ...GameplaySessionAttestationServiceTest.java | 148 +- .../common/security/GrpcClientAuthTest.java | 27 +- .../common/security/SessionClaimsTest.java | 100 ++ .../SessionContextTenantAccessTest.java | 24 +- .../security/AuthTokenInterceptorTest.java | 67 +- .../security/HttpJwtAuthInterceptorTest.java | 49 +- .../common/security/JwtClaimsTest.java | 86 +- .../test/AccountRuntimeStubServerTest.java | 127 +- .../test/AccountRuntimeStubServer.java | 70 +- .../CommunicationAggregationService.java | 23 +- .../CommunicationAggregationServiceTest.java | 31 +- .../gamesession/client/AccountClient.java | 49 +- .../client/EntityManagementClient.java | 3 +- .../gamesession/client/GameLogicClient.java | 17 +- .../client/ModerationPolicyClient.java | 6 +- .../client/SocialGroupsClient.java | 55 +- .../command/text/FriendsCommandHandler.java | 93 +- .../command/text/LoginCommandHandler.java | 23 +- .../command/text/PlayCommandHandler.java | 51 +- .../command/text/WorldsCommandHandler.java | 7 + .../GameplayLocalPathReadinessProbe.java | 4 +- .../FriendMutationResultOutput.java | 6 +- .../FriendPresenceViewOutput.java | 2 +- .../service/SessionAuthenticationService.java | 3 + .../gamesession/service/SessionContext.java | 16 +- .../impl/AccountPresenceQueryServiceImpl.java | 42 +- .../service/impl/CommandServiceImpl.java | 20 +- ...GameSessionCommandControlPlaneService.java | 6 +- .../service/impl/GameSessionGrpcService.java | 30 +- .../RedisAccountRecentPresenceService.java | 31 +- ...RedisFirstPartyConnectContextRegistry.java | 9 +- .../impl/RedisGameplayPresenceService.java | 23 +- .../impl/RedisSessionContextService.java | 18 +- ...ommunicationWebSocketCrossServiceTest.java | 79 +- ...GameSessionApplicationIntegrationTest.java | 3 +- .../GameSessionLoginIntegrationTest.java | 11 +- ...essionWebSocketHandlerIntegrationTest.java | 31 +- .../gamesession/client/AccountClientTest.java | 121 +- .../client/EntityManagementClientTest.java | 34 +- .../client/GameLogicClientTest.java | 83 +- .../text/FriendsCommandHandlerTest.java | 333 ++-- .../command/text/LoginCommandHandlerTest.java | 120 +- .../command/text/PlayCommandHandlerTest.java | 419 +++-- .../text/SessionResumptionFlowTest.java | 11 +- .../text/TextCommandInterpreterTest.java | 15 +- .../text/WorldsCommandHandlerTest.java | 68 +- .../WorldsTextCommandDispatchHandlerTest.java | 14 +- .../GameplayLocalPathReadinessProbeTest.java | 52 +- .../TextPlayerOutputRendererTest.java | 4 +- .../SessionAuthenticationServiceTest.java | 46 +- .../service/SessionContextTest.java | 62 +- .../AccountPresenceQueryServiceImplTest.java | 166 +- .../service/impl/CommandServiceImplTest.java | 97 +- ...tGameplayPresenceLifecycleServiceTest.java | 62 +- ...ameSessionControlPlaneGrpcServiceTest.java | 23 +- .../impl/GameSessionGrpcServiceTest.java | 188 +-- ...RedisAccountRecentPresenceServiceTest.java | 186 ++- ...sFirstPartyConnectContextRegistryTest.java | 23 + .../RedisGameplayPresenceServiceTest.java | 157 +- .../impl/RedisSessionContextServiceTest.java | 90 +- .../test/ChatTestFixturesTest.java | 26 +- .../test/GameplayCommandTestFixturesTest.java | 24 +- .../stubs/EntityManagementStubServerTest.java | 54 +- .../WebSocketOutputProjectorTest.java | 25 +- .../gamesession/CrossServiceAppHarness.java | 2 +- .../gamesession/test/ChatTestFixtures.java | 8 +- .../test/GameplayCommandTestFixtures.java | 132 +- .../test/GameplayPresenceTestFixtures.java | 45 +- .../GameplayCrossServiceStack.java | 4 +- .../testsupport/GameplayLoadScenarios.java | 3 +- .../loggingadmin/data/TestDataSeeder.java | 20 +- .../dto/ApplyModerationActionRequest.java | 9 +- .../dto/GameplayCommandStatusDto.java | 2 +- .../loggingadmin/dto/ModerationActionDto.java | 2 +- .../loggingadmin/entity/ModerationAction.java | 3 +- .../ModerationActionRepository.java | 5 +- .../service/ModerationService.java | 3 +- .../GameplayCommandStatusServiceImpl.java | 15 +- .../service/impl/LoggingAdminGrpcService.java | 7 +- .../service/impl/ModerationServiceImpl.java | 8 +- .../service/impl/ReportGrpcService.java | 8 +- .../service/impl/SessionActorReaders.java | 8 +- .../migration/V5__moderation_account_uuid.sql | 18 + ...tUuidMigrationPostgresIntegrationTest.java | 95 ++ .../ModerationActionControllerTest.java | 9 +- .../loggingadmin/data/TestDataSeederTest.java | 10 +- .../service/impl/AccountUuidReceiverTest.java | 150 ++ .../impl/AdmissionPointerServiceImplTest.java | 16 +- .../GameplayCommandStatusServiceImplTest.java | 28 +- .../impl/LoggingAdminGrpcServiceAuthTest.java | 32 +- .../impl/ModerationServiceImplTest.java | 22 +- .../service/impl/ReportGrpcServiceTest.java | 20 +- .../social-groups-service/build.gradle.kts | 1 + .../socialgroups/client/AccountClient.java | 68 +- .../client/GameSessionClient.java | 12 +- .../client/LoggingAdminClient.java | 6 +- .../client/ModerationPolicyClient.java | 4 +- .../controller/FriendController.java | 13 +- .../controller/MailController.java | 2 +- .../dto/AccountFriendLinkDto.java | 4 +- .../socialgroups/dto/AddFriendRequest.java | 10 +- .../dto/AddGuildMemberRequest.java | 9 +- .../socialgroups/dto/ChatMessageDto.java | 4 +- .../socialgroups/dto/CreateGuildRequest.java | 9 +- .../socialgroups/dto/FriendLinkDto.java | 4 +- .../socialgroups/dto/FriendPresenceDto.java | 10 +- .../dto/FriendRosterEntryDto.java | 4 +- .../firemud/socialgroups/dto/GuildDto.java | 2 +- .../socialgroups/dto/GuildMemberDto.java | 2 +- .../socialgroups/dto/MailMessageDto.java | 4 +- .../socialgroups/dto/SendMailRequest.java | 13 +- .../dto/SendMessageRequestDto.java | 15 +- .../UpdateFriendPresencePolicyRequest.java | 9 +- .../dto/UpdateGuildMemberRoleRequest.java | 9 +- .../dto/VoiceTokenRequestDto.java | 9 +- .../entity/AccountFriendLink.java | 4 +- .../socialgroups/entity/ChatMessage.java | 4 +- .../firemud/socialgroups/entity/Guild.java | 2 +- .../socialgroups/entity/GuildMember.java | 2 +- .../socialgroups/entity/MailMessage.java | 4 +- .../AccountFriendLinkRepository.java | 43 +- .../repository/ChatMessageRepository.java | 23 +- .../repository/GuildMemberRepository.java | 15 +- .../repository/GuildRepository.java | 10 +- .../JooqSocialGroupsRepositorySupport.java | 16 + .../repository/MailMessageRepository.java | 22 +- .../security/SocialAccessGuard.java | 19 +- .../socialgroups/service/ChatService.java | 2 +- .../socialgroups/service/FriendService.java | 23 +- .../socialgroups/service/GuildService.java | 2 +- .../service/impl/ChatServiceImpl.java | 16 +- .../service/impl/FriendServiceImpl.java | 80 +- .../service/impl/GuildServiceImpl.java | 4 +- .../service/impl/SocialGroupsGrpcService.java | 52 +- .../V10__canonical_account_uuid_carriers.sql | 72 + .../src/main/resources/openapi.yaml | 158 +- ...ocialGroupsApplicationIntegrationTest.java | 379 +++-- ...tUuidMigrationPostgresIntegrationTest.java | 277 ++++ .../client/AccountClientTest.java | 121 +- .../SocialInternalGrpcClientAuthTest.java | 9 +- .../controller/ChatControllerTest.java | 7 +- .../controller/FriendControllerTest.java | 203 ++- .../controller/GuildControllerTest.java | 11 +- .../controller/MailControllerTest.java | 26 +- .../controller/VoiceChatControllerTest.java | 14 +- .../dto/SocialAccountUuidRequestTest.java | 73 + .../security/SocialAccessGuardTest.java | 40 +- .../service/impl/ChatServiceImplTest.java | 68 +- .../service/impl/FriendServiceImplTest.java | 419 +++-- .../service/impl/GuildServiceImplTest.java | 31 +- .../service/impl/MailServiceImplTest.java | 10 +- .../impl/SocialGroupsGrpcServiceTest.java | 269 +++- .../impl/VoiceChatServiceImplTest.java | 3 +- .../test/AccountUuidFixtures.java | 12 + .../filter/JwtAuthFilterTest.java | 44 +- ...ionAccountCrossServiceIntegrationTest.java | 35 +- 193 files changed, 8528 insertions(+), 2444 deletions(-) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AuthenticationResultTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountRuntimeConsumerAuthWiringTest.java create mode 100644 services/logging-admin-service/src/main/resources/db/migration/V5__moderation_account_uuid.sql create mode 100644 services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountUuidReceiverTest.java create mode 100644 services/social-groups-service/src/main/resources/db/migration/V10__canonical_account_uuid_carriers.sql create mode 100644 services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialAccountUuidMigrationPostgresIntegrationTest.java create mode 100644 services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/dto/SocialAccountUuidRequestTest.java create mode 100644 services/social-groups-service/src/testFixtures/java/net/firedevops/firemud/socialgroups/test/AccountUuidFixtures.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index e1f2ed85cd..9414c362e2 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -106,6 +106,8 @@ The unregistered canonical `Authenticate` receiver requires the exact same-names `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. +In the ordinary Account gRPC methods, Account-valued selectors and authentication/bootstrap results use canonical Account UUID text, including `Authenticate`, `IssuePlayerBootstrapToken`, `GetProfile`, and `UpdateProfile`. For these operations Account resolves UUID selectors to numeric rows only for local storage access; the row is not exposed as the Account identity. Separate internal identity-provenance reads retain their own contract. `InternalRuntimeController`'s privileged numeric realm-grant management DTOs remain a separate unconverted boundary; see the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-account-uuid-receiving-preparation). + - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `account_service.proto`. - `CreateAccount` – registers a global Account identity and returns its canonical UUID as REST `AccountDto.id` and gRPC `CreateAccountResponse.account_id`; its platform audit outbox payload carries the same UUID. It does not select a tenant or create membership/profile state. - `SendNotification` – deliver account notifications asynchronously. @@ -243,6 +245,8 @@ The prepared original activation-protection methods authenticate the exact same- ## REST APIs +Implemented Account-valued REST selectors and response fields use canonical Account UUID text. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, and `ProfileDto.accountId` serialize as JSON strings; Account-issued login and bootstrap tokens carry the same UUID in `sub` and `accountId`. Current `/accounts/{accountId}` and profile handlers resolve those identities through Account's persisted UUID/provenance boundary before using private local rows. Tenant identifiers retain their existing representation. The Account identity contract is owned here with [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md); this paragraph records the local wire and storage boundary. + | Method | Path | Description | | --- | --- | --- | | `GET` | `/ping` | Simple health check | @@ -289,6 +293,8 @@ The prepared original activation-protection methods authenticate the exact same- | `GET` | `/support/tenants/{tenantId}/entitlements` | Cross-tenant support-safe entitlement view with redacted fields | | `GET` | `/.well-known/jwks.json` | JWKS for verifying issued JWTs | +The listed Account UUID representation does not imply full receiver convergence. Numeric legacy fields and privileged internal Account surfaces remain separate gaps; see the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-account-uuid-receiving-preparation). + Current verification routing/auth status: `POST /auth/verify-email` inherits bearer authentication because both HTTP configurations allowlist only `GET /auth/verify-email`, while that allowlisted GET has no controller mapping; see the existing [verification-routing gap in Runtime and Data](./runtime-and-data.md#email-and-notification-design). Current recovery/verification response and delivery behavior: password-reset, username-recovery, and public email-verification initiation retain the same neutral HTTP success for known and unknown normalized email addresses, including when a known-account post-commit SMTP send throws and is caught/logged; unknown addresses create no token or delivery attempt. This equal outcome does not remove the timing oracle: known-account sends still run synchronously after commit. Durable asynchronous delivery is absent, and focused service-level exception tests do not prove HTTP-level timing parity or timing resistance. This is not full account-enumeration resistance. @@ -297,7 +303,7 @@ The target `POST /auth/connect-token` REST response body is metadata-only: it co For the bootstrap-character and connect-token REST routes, authenticated gameplay-admission denials (`CONNECT_TOKEN_REJECTED`, `NON_PUBLIC_ENROLLMENT_REQUIRED`, `PUBLIC_PRODUCTION_ADMISSION_DENIED`, `JOIN_REQUIRED`, and `TENANT_BILLING_BLOCKED`) map to HTTP 403; invalid bootstrap credentials remain 401 and unavailable authority remains 503. -Current authentication, profile, membership, and tenant response examples retain numeric identifiers. Registration `AccountDto.id` and the Account component of the existing Account-local exports carry canonical Account UUIDs; profile and tenant identifiers in those exports remain unchanged. This bounded output change does not claim full portable export or complete ADR 0020 wire migration. +Registration `AccountDto.id`, authentication and player-bootstrap `accountId` results, the Account component of the current Account-local exports, and `ProfileDto.accountId` carry canonical Account UUIDs. Profile and tenant `tenantId` values remain unchanged. This bounded output change does not claim full portable export or complete ADR 0020 wire migration. Canonical current `/auth/login` success shape: @@ -305,7 +311,7 @@ Canonical current `/auth/login` success shape: { "status": "SUCCESS", "data": { - "accountId": 42, + "accountId": "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "authToken": "jwt-token-here" } } diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 8f34f4ebce..6458f0bd04 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -44,7 +44,7 @@ The source preparation also includes unregistered, caller-transaction-bound crea Account's actor-staging eligibility owner read is a read-only, same-namespace Entity workload RPC gated off by default. Under one repeatable-read Account transaction it verifies persisted Account UUID/provenance, current Account membership and pair authority, fresh Game Design tenant-source evidence, and the current membership event/checkpoint, then returns digest-sealed evidence scoped to `PUBLIC_PRODUCTION_STAGING_ONLY`. It reports an eligible or ineligible source snapshot but creates no membership, actor assignment, JOIN, PLAY, or gameplay admission. The staged foundation passed 43 focused Account tests and 92 shared-evidence tests with no failures or skips, plus source generation and Account integration-source compilation. PostgreSQL migration/persistence proof sources are included but physical PostgreSQL and live runtime execution remain unrun; the RPC is not runtime-ready or admission authority. -Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST/gRPC and the Account component of the current Account/profile-local and legacy tenant exports expose that persisted UUID through `AccountDto.id`; the mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and new registration audit payloads use the same UUID. Profile and tenant DTO identifiers, authentication results, JWT subjects, and downstream consumers remain unchanged; the current export is still partial Account/profile-local data, not the canonical portable export. The Account-local UUID-to-row resolver also remains confined to Account. The closed consumer boundary is incomplete: shared `SessionContext.currentAccountIdOrNull()` still requires numeric claims and is used by `GrpcClientAuth`, Logging & Admin `SessionActorReaders`, Automation Scripting `ScriptEventIngressServiceImpl`, and Social & Groups current-account authorization; Game Session control-plane owner authorization also compares numeric owner IDs. These consumers are outside this Account-owned slice, so no UUID-authentication or downstream-consumer proof is claimed. Focused repository and retained-row migration integration cases are present, but local PostgreSQL execution is unavailable while Docker is disabled; [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. +Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST/gRPC and the Account component of the current Account/profile-local and legacy tenant exports expose that persisted UUID through `AccountDto.id`; the mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and new registration audit payloads use the same UUID. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, the Account UUID in Account-issued JWT `sub`/`accountId` claims, and `ProfileDto.accountId` now carry the persisted UUID. Account's UUID-to-row resolver reads by that UUID and verifies its persisted provenance and source-row binding before returning the private numeric Account row used by local storage operations; that row is not an API identity. Tenant IDs and profile tenant identifiers retain their current representation. This bounded Account change does not migrate every consumer: retained numeric Redis session records remain fail-closed, and full JWT profile/registry behavior and remaining receiver proof are still incomplete; see the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-account-uuid-receiving-preparation). The current export is still partial Account/profile-local data, not the canonical portable export. Focused repository and retained-row migration cases remain distinct from the current ordinary receiving proof recorded in that tracker; [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. The account lifecycle state machine, global deletion preconditions, account-scoped versus tenant-scoped portable-data export split, separate safety-restriction lifecycles, hosting-billing authority, and future-marketplace `purchase_entitlement` substrate are the canonical target design. The current service has live identity/authentication, profile, external-link persistence, recovery/verification, payment, subscription, notification, and virtual-currency foundations, but lifecycle state transitions, genuine provider authentication, cross-service export, retained-record handling, complete account lock/platform-ban enforcement, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial. The current account export returns only Account and profile rows, the tenant export includes excessive global Account fields, and DeleteAccount preserves its JOIN and billing denials before failing closed without deleting child rows; AccountRepository retains its independent hard-delete guard. A complete retained-data lifecycle remains absent. Those behaviors directly conflict with [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and the bounded erasure workflow below. @@ -97,7 +97,7 @@ The unregistered canonical gameplay LOGIN primary-credential adapter reuses Acco ## Data Model -- `account` table stores username, password hash, email, and status flags for the global platform account, with an immutable unique non-nil `account_uuid`, its provenance, and the unchanged numeric source-row id added by V29. The numeric source-row id remains Account-local; registration and the Account portion of current Account-local exports expose the UUID as described in [Account API Contracts](./api-contracts.md). Authentication outputs and downstream session carriers do not yet use the UUID. +- `account` table stores username, password hash, email, and status flags for the global platform account, with an immutable unique non-nil `account_uuid`, its provenance, and the unchanged numeric source-row id added by V29. The numeric source-row id remains Account-local; registration and the Account portion of current Account-local exports expose the UUID as described in [Account API Contracts](./api-contracts.md). Ordinary authentication results, JWT account subjects, and profile Account fields now use the UUID; the numeric row remains private and is resolved only by Account. This does not establish full downstream receiver convergence; see [Account API Contracts](./api-contracts.md) and the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-account-uuid-receiving-preparation). - Target `profile` relationships are tenant-scoped and keyed exactly by `{accountId, tenantId}`; profile reads/writes require the corresponding membership and exact tenant filter. Any legacy account-only profile shape is implementation drift and must not authorize or expose a tenant relationship. - Target `achievement` relationships are tenant-scoped and keyed exactly by `{tenantId, accountId, achievementId}` (with any additional version/effect identity carried separately); the legacy “account and game” wording/shape is implementation drift because `game` is not an authority identifier. - Target `external_account` records link a server-verified canonical `{provider, issuer, subject}` to one global platform account without tenant scope. The current tenant-scoped, caller-asserted row shape is implementation drift. diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index c9d496764e..cec8f87e82 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -62,6 +62,8 @@ The local API surface retains only Logging & Admin consequences of the owner con - An appeal may be initiated from gameplay only through an opaque short-lived HTTPS handoff whose Account-authenticated intent binds the appellant, case/restriction revision, action, expiry, and stable dedicated appeal-submission request identity. That identity is persisted and correlated with `appealCaseId` for status and is distinct from any later dedicated `ownerEnforcementRequestId`; `controlPlaneRequestId` remains correlation-only on both moderation transports and cannot carry or alias either identity. The gameplay API cannot collect evidence or decide an appeal. - `UPHELD` has no owner mutation. `MODIFIED` and `OVERTURNED` retain the appeal linkage and forward a new digest-bound command to the existing enforcement owner; Logging & Admin does not directly clear or rewrite owner state. `DECIDED` is the terminal case fact, distinct from the subsequent owner-command outcome, which uses ADR 0048's phase-qualified states. Caller-facing status may report phase-qualified pending, committed, failed, or not-executed owner execution, or `RETRYABLE` guidance to poll/retry reconciliation for the same dedicated `ownerEnforcementRequestId`/digest; `RETRYABLE` is not a persisted or rearm state, and lost acknowledgement is reconciled with that same dedicated command identity/digest. +The current moderation receiver wire uses Account UUID text for the target `accountId`, `EvaluateModerationPolicy.account_id`, and the reporter/optional target fields on the internal `CreateReport` gRPC request. These local field semantics follow the [Account API](../account-service/api-contracts.md) and [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). The moderation-policy read passes the UUID to its repository; the mutation and report receiver paths remain fail-closed/unavailable. This does not convert the separate legacy numeric Account fields in `log_events` and `player_reports` DTO/storage paths or establish report persistence. + ## REST - Current `GET /ping` – privileged Bearer JWT-protected basic health check returning an `ApiResponse` with `data: "pong"`. HTTP access accepts either a global privileged role or an applicable tenant-scoped privileged role; missing/invalid credentials return `401`, and authenticated callers without either role return `403`. The gRPC `Ping` Bearer-JWT interceptor remains unchanged. The target classification remains Public/infra health under platform health policy; the HTTP route has not converged to that target. @@ -157,7 +159,7 @@ curl -H 'Authorization: Bearer ' \ - Activation remains blocked on this family's owner registry and approved finite schedule, including subject/tenant export, erasure or minimization, legal holds, backups and restore reconciliation. Its nonterminal reservations are live/recoverable work; any future terminal receipts and recovery lineage need cross-owner retry/restore-safe watermarks, while audit reason and client IP require purpose-bound governance and payload minimization. Post-authorization evidence also includes token identifiers and authorization-reference fingerprints, not the opaque reference itself. Proof-qualified terminalization, dependent-owner closure, tombstone/anti-replay preservation and bounded cleanup are still missing; the existing DELETE/TRUNCATE protections remain intact. Isolated run-owned tests cannot satisfy or enable this production activation gate. - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in [`logging_admin_service.proto`](../../../../protos/logging-admin/v1/logging_admin_service.proto); the current gRPC interceptor requires a Bearer JWT, while the target classification remains platform health policy. - `QueryLogs(QueryLogsRequest) returns (QueryLogsResponse)` – queries the service-owned PostgreSQL `log_events` table for the exact tenant and case-insensitive message containment and returns matching stored messages; it does not query the deployed structured-log pipeline. -- `ApplyModerationAction(ApplyModerationActionRequest) returns (ApplyModerationActionResponse)` – unavailable/gated implementation contract for moderation policy input/audit until the action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account authorization-reference issuance, and receiving-boundary validation/redemption exist; it now hard fails closed with an application-level `UNAVAILABLE` error before dispatch or persistence, while separate fixed-category policy/audit evidence and owner enforcement are absent, and it is not current supported external operator mutation. Target behavior uses one Account reference bound to the exact request identity/digest and redeemed exactly once by Logging & Admin for local policy-input/audit persistence; that reference is never forwarded or reused. Any future owner-enforcement command uses a separate Account reference redeemed once by its receiving owner. `EvaluateModerationPolicy` remains the live read contract used at owner enforcement boundaries and carries no mutation authorization reference. +- `ApplyModerationAction(ApplyModerationActionRequest) returns (ApplyModerationActionResponse)` – unavailable/gated implementation contract for moderation policy input/audit until the action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account authorization-reference issuance, and receiving-boundary validation/redemption exist; its current UUID-valued `accountId` is checked before it hard fails closed with an application-level `UNAVAILABLE` error before dispatch or persistence. Separate fixed-category policy/audit evidence and owner enforcement are absent, and this is not a supported external operator mutation. Target behavior uses one Account reference bound to the exact request identity/digest and redeemed exactly once by Logging & Admin for local policy-input/audit persistence; that reference is never forwarded or reused. Any future owner-enforcement command uses a separate Account reference redeemed once by its receiving owner. `EvaluateModerationPolicy` remains the live read contract used at owner enforcement boundaries and carries no mutation authorization reference. - `CreateModerationAppeal` / `GetModerationAppeal` – target-only bounded case submission and status reads. Logging & Admin owns case/evidence/jurisdiction/review state; Account supplies authenticated browser handoff and notifications, while any modified or overturned result returns a separate owner-command outcome rather than mutating enforcement locally. `DECIDED` is the terminal case fact; owner execution uses ADR 0048's phase-qualified states, and `RETRYABLE` is guidance to poll/retry reconciliation for the same command identity/digest only. No current implementation or proof is claimed. - `EvaluateModerationPolicy(EvaluateModerationPolicyRequest) returns (EvaluateModerationPolicyResponse)` – live internal owner-boundary read, not external operator or admin-UI availability. The current proto inventory is: @@ -180,8 +182,8 @@ curl -H 'Authorization: Bearer ' \ } ``` - Game Session calls it with `GAMEPLAY_ADMISSION`; Social & Groups calls it with `CHAT_SEND`. The current wire carries only `tenant_id`, `account_id`, and the broad `scope` value, so it cannot select or prove exact realm- or channel-scoped restrictions. Those scoped categories remain unavailable/unproven until trusted scope identities or owner-local projections exist. The target `internal_workload` contract requires exact allowlisted Game Session and Social & Groups workload identities over internal mTLS and rejects end-user JWTs, `control-ui` tokens, and operator authorization references. The interim receiver rejects non-internal JWTs and service names outside that allowlist, and the Social & Groups client emits an internal-service JWT for this call; certificate-derived exact workload/method authorization remains unproved. Treat the live call as a compatibility read, not evidence that the target authorization contract is implemented. The read remains live independently of observability backends, and applicable high-risk enforcement fails closed when the result is unavailable or not fresh. -- `logging_admin.v1.ReportService/CreateReport` – internal report persistence. Its `CreateReportRequest` and `CreateReportResponse` messages carry caller-supplied tenant, reporter, and optional target identities as data references only; they do not authorize a caller. The interim receiver accepts only an internal-service JWT naming `social-groups-service`, and the Social & Groups client emits that identity; certificate-derived exact mTLS workload/method authorization remains unproved, so this is interim hardening rather than target conformance. This gRPC contract is not public HTTP or player submission ingress. + Game Session calls it with `GAMEPLAY_ADMISSION`; Social & Groups calls it with `CHAT_SEND`. The current wire carries only `tenant_id`, `account_id`, and the broad `scope` value, so it cannot select or prove exact realm- or channel-scoped restrictions. `account_id` is Account UUID text and is validated before the UUID-valued subject reaches the moderation repository; `tenant_id` remains positive numeric text. Those scoped categories remain unavailable/unproven until trusted scope identities or owner-local projections exist. The target `internal_workload` contract requires exact allowlisted Game Session and Social & Groups workload identities over internal mTLS and rejects end-user JWTs, `control-ui` tokens, and operator authorization references. The interim receiver rejects non-internal JWTs and service names outside that allowlist, and the Social & Groups client emits an internal-service JWT for this call; certificate-derived exact workload/method authorization remains unproved. Treat the live call as a compatibility read, not evidence that the target authorization contract is implemented. The read remains live independently of observability backends, and applicable high-risk enforcement fails closed when the result is unavailable or not fresh. +- `logging_admin.v1.ReportService/CreateReport` – legacy internal report receiver seam. Its `CreateReportRequest` carries tenant, reporter, and optional target Account identities as data references only; it does not authorize a caller. The receiver validates the reporter and optional target as Account UUID text, then returns `UNAVAILABLE` before report persistence. The interim receiver accepts only an internal-service JWT naming `social-groups-service`, and the Social & Groups client emits that identity; certificate-derived exact mTLS workload/method authorization remains unproved, so this is interim hardening rather than target conformance. This gRPC contract is not public HTTP or player submission ingress, and its UUID fields do not convert the legacy `player_reports` DTO/storage fields. - `ToggleFeatureFlag(ToggleFeatureFlagRequest) returns (ToggleFeatureFlagResponse)` – target owner-forwarding contract, unavailable until the minimum schema/authorization gate above and the complete [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) durable, idempotent, fenced owner-execution contract are implemented and proved. The current gRPC ingress preserves admin-role, positive-tenant, and feature-name validation, then returns an application-level `UNAVAILABLE` error without invoking a service or owner. Once enabled, Logging & Admin is the audited forwarding ingress; Game Session owns the feature-flag mutation and its durable result. - Tick-remediation is not a Logging & Admin-owned state-mutation gRPC surface. Its HTTP ingress is hard fail closed and no Logging & Admin pause/resume forwarding method remains callable internally; the target owner contract remains unavailable until the minimum schema/authorization gate above and the complete [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) durable, idempotent, fenced owner-execution contract are implemented and proved. Once enabled, Logging & Admin audits and forwards to Game Session, which owns tick state, fencing, idempotency, and the durable result. Future recovery operations require separate named typed owner contracts; no generic `remediate` RPC is reserved. @@ -199,7 +201,7 @@ grpcurl -cacert "$FIREMUD_GRPC_CA_CERT_PATH" \ -cert "$FIREMUD_GRPC_CERT_CHAIN_PATH" \ -key "$FIREMUD_GRPC_PRIVATE_KEY_PATH" \ -H 'Authorization: Bearer ' \ - -d '{"tenant_id":"1","reporter_account_id":"1","target_account_id":"2","type":"BUG","description":"example"}' \ + -d '{"tenant_id":"1","reporter_account_id":"e830a76a-a786-43de-9416-5840fa6e0578","target_account_id":"b8d093f7-cb70-40ed-9fac-3c82d4bf28f1","type":"BUG","description":"example"}' \ "$FIREMUD_LOGGING_ADMIN_GRPC_TARGET" \ logging_admin.v1.ReportService/CreateReport ``` diff --git a/design/architecture/microservices/logging-admin-service/runtime-and-data.md b/design/architecture/microservices/logging-admin-service/runtime-and-data.md index 52a4809b29..af779a5d1f 100644 --- a/design/architecture/microservices/logging-admin-service/runtime-and-data.md +++ b/design/architecture/microservices/logging-admin-service/runtime-and-data.md @@ -115,6 +115,7 @@ For plugin operations, Automation remains the activation/lifecycle owner and Gam - `log_events` is the current service-owned PostgreSQL domain table. `LogQueryServiceImpl` queries it by exact `tenantId` and case-insensitive message containment and returns only stored messages. No current implementation mirrors this table into Elasticsearch or proves the profile-aware emitter-to-query path; selected-profile indexed, compatible-backend, or console/journal querying remains target-state under [Logging & Monitoring](../../system-architecture-logging-monitoring.md#log-pipeline-queryability-contract). - `moderation_actions` is the target durable record for accepted moderation policy intent and audit evidence, with the fixed category, normalized explicit scope, actor/case/source request, safe notice/reason, local intent-reference redemption outcome, separate owner command/result linkage when a later enforcement command exists, and the idempotency identity, digest, and timestamps. A linked owner-result revision is recorded only when that result supplies it; the local policy-intent commit never synthesizes owner revision or enforcement epoch. Raw authorization references are never persisted. The legacy `POST /moderation/actions` and `ApplyModerationAction` transport stubs now hard fail closed after narrow checks without persisting their generic legacy row; they are unsupported/nonconformant and not target fixed-category proof. Owner restriction tables and owner-command redemption are separate; Logging & Admin does not mutate them. +- Forward V5 changes the local `moderation_actions.account_id` column to UUID and adds a non-nil constraint only after an access-exclusive table lock and an empty-table guard. Any retained row makes the migration fail before alteration; it supplies no Account-owner mapping, backfill, or deletion path. A populated deployment therefore requires a genuine Account-owner mapping and explicit retained-data disposition before migration. This is receiver/storage preparation only; the current moderation mutation remains fail-closed and does not persist rows. - `moderation_appeal_cases` and bounded `moderation_appeal_evidence_refs` are target Logging & Admin records for the `SUBMITTED -> UNDER_REVIEW -> DECIDED` lifecycle, exact appealed owner revision/digest, jurisdiction, eligibility policy, safe submission/decision, bounded evidence references, retention/legal-hold/export state, and resulting owner command identity. No complete appeal table or workflow is currently implemented. - `player_reports` is the target durable store for abuse and bug reports accepted through the report-persistence seam, including tenant scope in its `tenant_id` column. Current report persistence is unavailable: both the internal `CreateReport` ingress and the service-layer mutation fail closed before any repository save, and public administrative and target caller-bound external/player submission remain unavailable. - Runtime feature-flag truth is owned by Game Session. After the action-family schema, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance plus owner-side redemption gate passes, Logging & Admin records operator intent and audit context for feature-flag requests, then forwards the mutation to Game Session rather than maintaining a competing `feature_flag` runtime table. diff --git a/design/architecture/microservices/social-groups-service/api-contracts.md b/design/architecture/microservices/social-groups-service/api-contracts.md index 5894635e65..a73cbb9bfc 100644 --- a/design/architecture/microservices/social-groups-service/api-contracts.md +++ b/design/architecture/microservices/social-groups-service/api-contracts.md @@ -4,6 +4,10 @@ This document defines the Social & Groups Service REST and gRPC surfaces, chat-d An OpenAPI specification for the REST endpoints is available at `src/main/resources/openapi.yaml` in the service repository. +## Account Identity Fields + +Social REST and gRPC Account-valued fields and path selectors use Account UUID text, including friend and presence identities, guild owner/member identities, chat and mail sender/recipient identities, and voice-token account selectors. `tenantId` retains its current numeric representation. The [Account API](../account-service/api-contracts.md) and [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) own the identity contract; this section records Social's local wire-field consequence. It does not change the availability or player-safety status of the service-local and Gateway routes described below. + ## Chat and Moderation Contract **Target state:** Social & Groups is the enforcement owner for `chat_mute` and `chat_ban`. Its local indexed restriction state is evaluated before chat persistence/publication and at participation/history reads; the complete category, revision, command, notice, and appeal-outcome contract is [Moderation Policies](../logging-admin-service/moderation-policies.md) and active [ADR 0146](../../decisions/adr-0146-owner-local-moderation-enforcement.md), mapped from reviewed archive record `archive-ADR-0133`. Every REST and gRPC chat write must traverse that same owner-local restriction boundary before persistence or publication. `chat_mute` rejects sending but permits ordinary receipt, while `chat_ban` rejects ordinary participation, send, and history but permits essential moderation/system notices. @@ -55,7 +59,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":"b8d093f7-cb70-40ed-9fac-3c82d4bf28f1","content":"hello"}' ``` Example voice-token request: @@ -64,7 +68,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":"b8d093f7-cb70-40ed-9fac-3c82d4bf28f1","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..68a936c9e5 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,7 @@ The current live moderation seam is the synchronous `EvaluateModerationPolicy` r ## Data Model +- **Current Account UUID storage preparation:** jOOQ-backed Account carriers in `guilds.owner_account_id`, `guild_members.account_id`, `chat_messages` sender/recipient fields, `friend_links` endpoints, `mail_messages` sender/recipient fields, and `account_friend_links` endpoints use UUID columns after V10. The migration locks all affected tables and refuses to proceed if any contains rows; it changes the column types only after the empty-table guard, with no retained-row mapping, backfill, or deletion. A populated deployment therefore needs a genuine Account-owner mapping and explicit retained-data disposition before migration; numeric values are never guessed into Account UUIDs. This local storage preparation does not change numeric tenant IDs or the separately documented relationship and route gaps. - 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/ai-observations.md b/design/project-management/ai-observations.md index 074367b126..89cd21a160 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -706,6 +706,7 @@ Gameplay #3310 Hosted7 finished at 03:51:18 NZDT but its native evidence was rec - Observation: The 25-minute 28-second gap preceded first observation; its cause is unknown. This differs from the earlier observed-but-unreported #3327 result. Neither the provider finish time nor an active observer alone proves timely detection, and no FireController latency cause is established. - Expected pattern: Retain provider-finish, first-observation and owner-handoff times separately. Prioritize the front's substantive run on a bounded per-target observation schedule while independent review waits continue; skip repeated calls to an already known incompatible client endpoint and preserve the one-observer boundary. - Outcome: Main selected approximately 90-second front checks and five-minute successor checks, with prompt failure/terminal handoffs and the supported bound CLI for incompatible operation reads. Improved detection latency has not yet been separately measured. + - Recurrence (`2026-10-30`): #3346 Hosted2 actually ran from 10:18:40 to 10:31:03 NZDT and was retained at 10:31:12.989, while the sentinel handed it off at 10:36:09. The delivery-only active diagnostic lacked provider-start evidence; it did not prove a stalled provider. Root corrected its stall report and restored prompt provider waits within the same shared observer. The roughly five-minute observation delay is distinct from the roughly ten-second capture delay; sustained recovery remains unmeasured. - `2026-10-30`: Keep front merge observation after CI becomes terminal - Context: #3331 merged at 09:19:31 NZDT while Gameplay continued successor fixes. Main had retired its completed CI observation without retaining front PR merge observation. @@ -718,3 +719,8 @@ Gameplay #3310 Hosted7 finished at 03:51:18 NZDT but its native evidence was rec - Observation: The edited event correctly named base5bae/head55e9, but mergea7a99263 retained parents a313/55e9. Runtime image-tag derivation and Preview identifier derivation refused that stale artifact, and native readiness reported ci_merge_base_mismatch. New images and smoke were not run. This differs from the earlier #3310 event whose base field was stale; no new root cause is established. - Expected pattern: Compare event identity, actual merge parents and stable live base separately, retain the failed runs and obtain the supported current-comparison recovery from the owning CI/tool lane. Old green or a dummy commit does not establish current-base proof. - Outcome: Exact evidence was reported to Overseer and FireController. A normal ancestry merge of the stable develop base produced `a00d9c0f8928` with a byte-identical source tree; the subsequent retained refresh verified the new test-merge identity. Current CI is separate and still pending. The tool owner installed diagnostic improvement `aeb84eaf`, explaining GitHub regeneration and repository-authorized reconciliation without claiming a controller refresh can regenerate GitHub refs. The original stale-artifact failure and unknown upstream cause remain retained. + +- `2026-10-30`: Retain proof when execution sessions disappear + - Observation: R1109 lost its exec session during static checks; metadata had no exit receipt, the log stopped, and no active Gradle process remained. Helper enumeration also returned only root while their retained paths still existed. The external interruption cause is unknown. + - Consequence: Completed native and unit XML remains separately attributable, but neither the unfinished static checks nor the aggregate can be counted as passed. + - Outcome: Root retained the incomplete log/metadata and fresh XML, verified no duplicate local run, and resumed the existing helper identities and sole observer with their original scopes. Focused recovery remains required; no provider or CI action was repeated. 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 c7068699c4..49450f529c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -460,6 +460,14 @@ The Account-authorized request flow forwarded to Game Session remains target-sta Live Account authentication hashes and verifies passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with character-array handling and post-use wiping. Profile, external-account persistence/service scaffolds, recovery and verification, notification, payment, subscription, and virtual-currency surfaces have live foundations; the unsupported caller-asserted external-link REST route is removed and denied at the public edge. The broader account lifecycle state machine, server-verified provider linking, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial or unavailable as tracked below. +#### Ordinary Account UUID receiving preparation + +Unpublished #2972 local source postimages move Account authentication and player-bootstrap results, issued JWT account subjects/claims, and profile Account fields to the persisted Account UUID. Account resolves UUID to a private numeric row only through its own persisted UUID, provenance, and source-row checks. Social REST/gRPC DTOs and jOOQ-backed Account carriers use UUID fields; Logging's ordinary moderation receiver uses Account UUIDs. Tenant identifiers retain their current numeric representation. These are local receiving consequences, not a published or review-ready capability. + +Social V10 and Logging & Admin V5 lock their affected legacy tables and refuse migration if any retained row exists. Neither migration deletes rows, guesses an Account UUID from a numeric value, or supplies a historical backfill; rollout against populated data requires a genuine Account-owner mapping and explicit retained-data disposition. Fixture Account associations are deterministic only in fake tests and provide no production mapping. Retained numeric Redis session carriers remain fail-closed. The privileged numeric realm-grant DTOs in `InternalRuntimeController`, legacy numeric `LogEvent`/`PlayerReport` fields, the numeric Account deletion client, and the exposed legacy Game Session StartSession owner DTO/proto Account fields remain outside ordinary UUID receiving convergence; no cross-service numeric Account value is treated as private Account provenance. Full JWT profile/registry qualification, default registration, source custody/PKI, and public admission/activation/first `OPEN` remain held and receive no bridge or status change from this preparation. + +Proof is partial and not an aggregate pass. R1101 retained its aggregate failure on the Account helper and jOOQ SQL parsing. R1108 compiled all ten affected modules and passed both jOOQ generations, 14 selected Account unit cases, and two native Logging empty/populated-migration-refusal cases, but failed aggregate execution when Social integration compilation could not see its fixture helper. After the helper was moved unchanged into test fixtures, R1109 passed seven Social native cases; its selected Account run had 22 failures among 344 cases from stale numeric/noncanonical JWT test fixtures and stale UUID gRPC selectors/messages/stubs. R1109 was interrupted during static checks with no exit receipt, so it remains an interrupted partial run, not an aggregate pass. R1110 passes 129 of the 131 selected Account receiver/MVC cases after fixture correction; R1111 separately passes the remaining two after correlating their signed subjects and claims, completing passing execution of all 344 distinct selected Account methods across these runs. R1111 also passes the selected Social fixture/integration and Account test static checks plus documentation, but its aggregate fails one Account main dead-store warning; removing only the unused local value retains the identity-resolution call, and that correction still needs static recovery. A real registration-to-login HTTP/JWT proof is prepared but unrun. No production defect is claimed from the corrected fixture failures, and current full-service qualification remains incomplete. + ### Text Protocol and Credential Policy Telnet and generic WebSocket clients share one Game Session line-oriented parser/interpreter and gameplay queue. The parser trims input, accepts case-insensitive command names, handles empty or malformed lines, and maps unknown commands to `UNKNOWN`; Telnet performs no separate gameplay parsing. The current canonical flow is optional `WORLDS`, `LOGIN`, `PLAY`, and gameplay commands such as `LOOK` and `SAY`, with built-in `LOGOUT`. `LOGON` remains an accepted login spelling where the protocol documents it. The old typed `SESSION` attach flow is not part of the canonical initial-development protocol; future smart-client metadata, if revived, is transport metadata rather than a player command and is never authoritative. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java index adc504c777..7ac5c0007c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java @@ -2,6 +2,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import jakarta.validation.Valid; +import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountDataExportDto; import net.firedevops.firemud.accountservice.dto.AccountDto; import net.firedevops.firemud.accountservice.dto.AccountLoginAuthModesDto; @@ -45,8 +46,9 @@ public ResponseEntity> createAccount( @GetMapping("/{accountId}/login-auth-modes") public ResponseEntity> getLoginAuthModes( @PathVariable String accountId) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); - requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); + requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountUuid); + Long parsedAccountId = accountService.resolveAccountStorageId(parsedAccountUuid); return ResponseEntity.ok( ApiResponse.success(accountService.getLoginAuthModes(parsedAccountId))); } @@ -56,8 +58,8 @@ public ResponseEntity> getLoginAuthModes( public ResponseEntity> updateLoginAuthModes( @PathVariable String accountId, @Valid @RequestBody UpdateAccountLoginAuthModesRequest request) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); - requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); + requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountUuid); throw new org.springframework.web.server.ResponseStatusException( HttpStatus.NOT_IMPLEMENTED, "Recent ordinary reauthentication is required; login-factor changes are unavailable until Account implements its evidence mechanism"); @@ -66,8 +68,9 @@ public ResponseEntity> updateLoginAuthMode @GetMapping("/{accountId}/export") public ResponseEntity> exportAccount( @PathVariable String accountId) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); - requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); + requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountUuid); + Long parsedAccountId = accountService.resolveAccountStorageId(parsedAccountUuid); AccountDataExportDto data = accountService.exportAccountData(parsedAccountId); return ResponseEntity.ok(ApiResponse.success(data)); } @@ -75,26 +78,35 @@ public ResponseEntity> exportAccount( @GetMapping("/{accountId}/tenant-export") public ResponseEntity> exportTenantData( @PathVariable String accountId, @RequestParam String tenantId) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); long parsedTenantId = AccountRequestReaders.requireTenantId(tenantId); - SessionContext.requireAccountAccess(parsedTenantId, parsedAccountId); + if (!isCurrentAccount(parsedAccountUuid) && !SessionContext.hasTenantAccess(parsedTenantId)) { + throw new org.springframework.web.server.ResponseStatusException( + HttpStatus.FORBIDDEN, "Account access required"); + } + Long parsedAccountId = accountService.resolveAccountStorageId(parsedAccountUuid); TenantDataExportDto data = accountService.exportTenantData(parsedTenantId, parsedAccountId); return ResponseEntity.ok(ApiResponse.success(data)); } @DeleteMapping("/{accountId}") public ResponseEntity> deleteAccount(@PathVariable String accountId) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); - requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); + requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountUuid); + Long parsedAccountId = accountService.resolveAccountStorageId(parsedAccountUuid); accountService.deleteAccount(parsedAccountId); return ResponseEntity.ok(ApiResponse.success(null)); } - private void requireCurrentAccountOrGlobalPrivilegedRole(Long accountId) { - if (SessionContext.isCurrentAccount(accountId) || SessionContext.hasGlobalPrivilegedRole()) { + private void requireCurrentAccountOrGlobalPrivilegedRole(UUID accountUuid) { + if (isCurrentAccount(accountUuid) || SessionContext.hasGlobalPrivilegedRole()) { return; } throw new org.springframework.web.server.ResponseStatusException( org.springframework.http.HttpStatus.FORBIDDEN, "Account access required"); } + + private static boolean isCurrentAccount(UUID accountUuid) { + return accountUuid.toString().equals(SessionContext.getAccountId()); + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountRequestReaders.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountRequestReaders.java index b328921644..a0acc080e9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountRequestReaders.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountRequestReaders.java @@ -1,10 +1,20 @@ package net.firedevops.firemud.accountservice.controller; +import java.util.UUID; +import net.firedevops.firemud.accountservice.AccountUuidText; import net.firedevops.firemud.common.security.RequestIdValidation; final class AccountRequestReaders { private AccountRequestReaders() {} + static UUID requireAccountUuid(String accountId) { + UUID parsed = AccountUuidText.parseOrNull(accountId); + if (parsed == null) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + return parsed; + } + static long requireAccountId(String accountId) { return RequestIdValidation.requirePositiveLong(accountId, "accountId"); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java index b0bc7c1015..df27c1be4c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java @@ -2,6 +2,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import jakarta.validation.Valid; +import java.util.UUID; import net.firedevops.firemud.accountservice.dto.ProfileDto; import net.firedevops.firemud.accountservice.dto.UpdateProfileRequest; import net.firedevops.firemud.accountservice.service.AccountService; @@ -33,19 +34,25 @@ public ProfileController(AccountService accountService) { @GetMapping("/{accountId}") public ResponseEntity> getProfile( @PathVariable String accountId, @RequestParam String tenantId) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); long parsedTenantId = AccountRequestReaders.requireTenantId(tenantId); - requireProfileOwner(parsedAccountId); + requireProfileOwner(parsedAccountUuid); + Long parsedAccountId = accountService.resolveAccountStorageId(parsedAccountUuid); ProfileDto dto = accountService.getProfile(parsedTenantId, parsedAccountId); + requireProfileResult(dto, parsedAccountUuid, parsedTenantId); return ResponseEntity.ok(ApiResponse.success(dto)); } @PutMapping("/{accountId}") public ResponseEntity> updateProfile( @PathVariable String accountId, @Valid @RequestBody UpdateProfileRequest request) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); long parsedTenantId = AccountRequestReaders.requireTenantId(request.tenantId()); - requireProfileOwner(parsedAccountId); + requireProfileOwner(parsedAccountUuid); + UUID bodyAccountUuid = AccountRequestReaders.requireAccountUuid(request.accountId()); + if (!parsedAccountUuid.equals(bodyAccountUuid)) { + throw new IllegalArgumentException("Profile path and body accountId must match"); + } if (request.presenceVisibilityPolicy() == null) { throw new IllegalArgumentException("presenceVisibilityPolicy must be provided"); } @@ -54,15 +61,25 @@ public ResponseEntity> updateProfile( accountService.updateProfile( new UpdateProfileRequest( parsedTenantId, - parsedAccountId, + parsedAccountUuid.toString(), request.displayName(), request.bio(), request.presenceVisibilityPolicy())); + requireProfileResult(dto, parsedAccountUuid, parsedTenantId); return ResponseEntity.ok(ApiResponse.success(dto)); } - private static void requireProfileOwner(long accountId) { - if (!SessionContext.isCurrentAccount(accountId)) { + private static void requireProfileResult(ProfileDto dto, UUID accountUuid, long tenantId) { + if (dto == null + || !accountUuid.toString().equals(dto.accountId()) + || !Long.valueOf(tenantId).equals(dto.tenantId())) { + throw new ResponseStatusException( + HttpStatus.SERVICE_UNAVAILABLE, "Profile authority unavailable"); + } + } + + private static void requireProfileOwner(UUID accountUuid) { + if (!accountUuid.toString().equals(SessionContext.getAccountId())) { throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Profile access required"); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AuthenticationResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AuthenticationResult.java index 978306a52f..e218c98e09 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AuthenticationResult.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AuthenticationResult.java @@ -1,4 +1,12 @@ package net.firedevops.firemud.accountservice.dto; +import net.firedevops.firemud.accountservice.AccountUuidText; + /** Result of a successful authentication attempt. */ -public record AuthenticationResult(long accountId, String authToken) {} +public record AuthenticationResult(String accountId, String authToken) { + public AuthenticationResult { + if (AccountUuidText.parseOrNull(accountId) == null) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/PlayerBootstrapResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/PlayerBootstrapResult.java index a029e6da93..d3eb6d032f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/PlayerBootstrapResult.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/PlayerBootstrapResult.java @@ -2,4 +2,4 @@ /** Result of issuing a short-lived first-party bootstrap token. */ public record PlayerBootstrapResult( - long accountId, String bootstrapToken, String issuedAt, String expiresAt) {} + String accountId, String bootstrapToken, String issuedAt, String expiresAt) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/ProfileDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/ProfileDto.java index 4a2ededcd4..8c7c3c25bd 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/ProfileDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/ProfileDto.java @@ -7,7 +7,7 @@ public record ProfileDto( Long id, @NotNull Long tenantId, - @NotNull Long accountId, + @NotNull String accountId, @Size(max = 100) String displayName, @Size(max = 255) String bio, @NotNull ProfilePresenceVisibilityPolicy presenceVisibilityPolicy) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/UpdateProfileRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/UpdateProfileRequest.java index b24378b729..9d6e0e4184 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/UpdateProfileRequest.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/UpdateProfileRequest.java @@ -6,7 +6,7 @@ public record UpdateProfileRequest( @NotNull Long tenantId, - @NotNull Long accountId, + @NotNull String accountId, @Size(max = 100) String displayName, @Size(max = 255) String bio, @NotNull ProfilePresenceVisibilityPolicy presenceVisibilityPolicy) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/ProfileMapper.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/ProfileMapper.java index 18137c1d66..ca080db0de 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/ProfileMapper.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/ProfileMapper.java @@ -3,11 +3,11 @@ import net.firedevops.firemud.accountservice.dto.ProfileDto; import net.firedevops.firemud.accountservice.entity.Profile; import org.mapstruct.Mapper; +import org.mapstruct.Mapping; import org.mapstruct.ReportingPolicy; @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) public interface ProfileMapper { - ProfileDto toDto(Profile entity); - - Profile toEntity(ProfileDto dto); + @Mapping(target = "accountId", source = "accountUuid") + ProfileDto toDto(Profile entity, String accountUuid); } 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 54bd0c6207..c674157e24 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -5,6 +5,7 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.time.Instant; import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AccountServiceGrpc; @@ -37,6 +38,7 @@ import net.firedevops.firemud.account.v1.UpdateProfileRequest; import net.firedevops.firemud.account.v1.UpdateProfileResponse; import net.firedevops.firemud.account.v1.VerifyEmailLoginOtpRequest; +import net.firedevops.firemud.accountservice.AccountUuidText; import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; @@ -54,11 +56,13 @@ import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.common.security.SessionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.grpc.server.service.GrpcService; +import tools.jackson.core.JacksonException; import tools.jackson.databind.JsonNode; import tools.jackson.databind.json.JsonMapper; @@ -107,17 +111,19 @@ public void issueDirectTextConnectScope( IssueDirectTextConnectScopeResponse.newBuilder(); try { requireGameSessionPeer(); - DirectTextCallerContext caller = directTextCaller(request.getPlayerContext()); + var context = request.getPlayerContext(); long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); UUID realmId = requireCanonicalRealmId(request.getRealmId()); long gameInstanceId = requirePositiveRequestId(request.getGameInstanceId(), "gameInstanceId"); - if (caller.tenantId() != tenantId - || !caller.realmId().equals(realmId) - || caller.gameInstanceId() != gameInstanceId - || !caller.playableStateNamespaceId().equals(request.getPlayableStateNamespaceId()) - || !caller.playableStateScope().equals(request.getPlayableStateScope())) { + if (requirePositiveRequestId(context.getTenantId(), "tenantId") != tenantId + || !requireCanonicalRealmId(context.getRealmId()).equals(realmId) + || requirePositiveRequestId(context.getGameInstanceId(), "gameInstanceId") + != gameInstanceId + || !context.getPlayableStateNamespaceId().equals(request.getPlayableStateNamespaceId()) + || !context.getPlayableStateScope().equals(request.getPlayableStateScope())) { throw new InvalidRequestException("Player context and selected realm disagree", null); } + DirectTextCallerContext caller = directTextCaller(context); var scope = accountService.issueDirectTextConnectScope( caller, @@ -160,23 +166,26 @@ public void joinPublicProductionMembership( JoinPublicProductionMembershipResponse.newBuilder(); try { requireGameSessionPeer(); - DirectTextCallerContext caller = directTextCaller(request.getPlayerContext()); String requestId = requireText(request.getRequestId(), "requestId"); if (requestId.length() > JoinPublicProductionRequest.MAX_REQUEST_ID_LENGTH) { throw new InvalidRequestException("JOIN requestId exceeds the maximum length", null); } - if (!requestId.equals(caller.requestId())) { + if (!requestId.equals(request.getPlayerContext().getRequestId())) { throw new InvalidRequestException("Player context and JOIN request ID disagree", null); } + DirectTextCallerContext caller = directTextCaller(request.getPlayerContext()); var result = accountService.joinPublicProductionFromGameSession( caller, new JoinPublicProductionRequest( requireText(request.getConnectScopeId(), "connectScopeId"), requestId)); + if (result.accountId() != caller.accountId() || result.tenantId() != caller.tenantId()) { + throw new IllegalStateException("Account JOIN result does not match the validated caller"); + } response .setSuccess(result.success()) .setOutcomeCode(result.outcomeCode()) - .setAccountId(Long.toString(result.accountId())) + .setAccountId(request.getPlayerContext().getAccountId()) .setTenantId(Long.toString(result.tenantId())) .setMembershipId(Long.toString(result.membershipId())) .setMembershipVersion(result.membershipVersion()) @@ -210,17 +219,72 @@ private void requireGameSessionPeer() { } } + private void requireRuntimeEntitlementsPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + String namespace = workloadNamespace; + if (peer == null + || namespace == null + || namespace.isBlank() + || !(peer.uri().equals("spiffe://firemud/ns/" + namespace + "/sa/game-session-service") + || peer.uri() + .equals("spiffe://firemud/ns/" + namespace + "/sa/world-management-service"))) { + throw new AdminAuthorizationException( + "Verified Game Session or World Management workload identity is required"); + } + } + + private void requireSocialGroupsPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || workloadNamespace == null + || workloadNamespace.isBlank() + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/social-groups-service")) { + throw new AdminAuthorizationException("Verified Social Groups workload identity is required"); + } + } + + private void requireCallerAccountSubject(UUID accountUuid) { + if (SessionContext.isInternalService()) { + throw new AdminAuthorizationException("Authenticated account subject is required"); + } + if (!accountUuid.toString().equals(SessionContext.getAccountId())) { + throw new AdminAuthorizationException("Profile access is restricted to the caller account"); + } + } + + private static UUID requireCanonicalAccountUuid(String value) { + UUID accountUuid = AccountUuidText.parseOrNull(value); + if (accountUuid == null) { + throw new InvalidRequestException("accountId must be a canonical non-nil UUID", null); + } + return accountUuid; + } + private DirectTextCallerContext directTextCaller( net.firedevops.firemud.shared.v1.PlayerExecutionContext context) { + UUID accountUuid = requireCanonicalAccountUuid(context.getAccountId()); + long tenantId = requirePositiveRequestId(context.getTenantId(), "tenantId"); + UUID realmId = requireCanonicalRealmId(context.getRealmId()); + String namespaceId = + requireCanonicalPlayableStateNamespaceId(context.getPlayableStateNamespaceId()); + String scope = requireText(context.getPlayableStateScope(), "playableStateScope"); + long gameInstanceId = requirePositiveRequestId(context.getGameInstanceId(), "gameInstanceId"); + String sessionId = requireText(context.getSessionId(), "sessionId"); + String requestId = requireText(context.getRequestId(), "requestId"); + long accountStorageId = accountService.resolveAccountStorageId(accountUuid); + if (accountStorageId <= 0L) { + throw new IllegalStateException("Account UUID did not resolve to a persisted owner"); + } return new DirectTextCallerContext( - requirePositiveRequestId(context.getAccountId(), "accountId"), - requirePositiveRequestId(context.getTenantId(), "tenantId"), - requireCanonicalRealmId(context.getRealmId()), - requireCanonicalPlayableStateNamespaceId(context.getPlayableStateNamespaceId()), - requireText(context.getPlayableStateScope(), "playableStateScope"), - requirePositiveRequestId(context.getGameInstanceId(), "gameInstanceId"), - requireText(context.getSessionId(), "sessionId"), - requireText(context.getRequestId(), "requestId")); + accountStorageId, + tenantId, + realmId, + namespaceId, + scope, + gameInstanceId, + sessionId, + requestId); } private UUID requireCanonicalRealmId(String value) { @@ -319,7 +383,7 @@ public void authenticate( AuthenticateResponse response = AuthenticateResponse.newBuilder() .setAuthToken(result.authToken()) - .setAccountId(String.valueOf(result.accountId())) + .setAccountId(result.accountId()) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); @@ -344,6 +408,13 @@ public void authenticate( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (IllegalStateException ex) { + AuthenticateResponse response = + AuthenticateResponse.newBuilder() + .setError(appError("Authenticate", "AUTH_UNAVAILABLE", AUTHORITY_UNAVAILABLE_MESSAGE)) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } } @@ -373,7 +444,7 @@ public void verifyEmailLoginOtp( responseObserver.onNext( AuthenticateResponse.newBuilder() .setAuthToken(result.authToken()) - .setAccountId(String.valueOf(result.accountId())) + .setAccountId(result.accountId()) .build()); } catch (InvalidRequestException ex) { responseObserver.onNext( @@ -389,6 +460,13 @@ public void verifyEmailLoginOtp( AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials")) .build()); + } catch (IllegalStateException ex) { + responseObserver.onNext( + AuthenticateResponse.newBuilder() + .setError( + appError( + "VerifyEmailLoginOtp", "AUTH_UNAVAILABLE", AUTHORITY_UNAVAILABLE_MESSAGE)) + .build()); } responseObserver.onCompleted(); } @@ -399,14 +477,22 @@ public void getTenantMembershipForRuntime( GetTenantMembershipForRuntimeRequest request, StreamObserver responseObserver) { try { + requireGameSessionPeer(); + UUID accountUuid = requireCanonicalAccountUuid(request.getAccountId()); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + long accountStorageId = accountService.resolveAccountStorageId(accountUuid); var dto = accountService.getTenantMembershipForRuntime( - requirePositiveRequestId(request.getAccountId(), "accountId"), - requirePositiveRequestId(request.getTenantId(), "tenantId"), - request.getRequestId()); + accountStorageId, tenantId, request.getRequestId()); + if (dto == null + || !Long.valueOf(accountStorageId).equals(dto.accountId()) + || !Long.valueOf(tenantId).equals(dto.tenantId())) { + throw new IllegalStateException( + "Account membership authority returned an inconsistent identity"); + } GetTenantMembershipForRuntimeResponse response = GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId(String.valueOf(dto.accountId())) + .setAccountId(accountUuid.toString()) .setTenantId(String.valueOf(dto.tenantId())) .setMembershipExists(dto.membershipExists()) .setGameplayAdmissionAllowed(dto.gameplayAdmissionAllowed()) @@ -417,6 +503,13 @@ public void getTenantMembershipForRuntime( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setError( + appError("GetTenantMembershipForRuntime", "PERMISSION_DENIED", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { GetTenantMembershipForRuntimeResponse response = GetTenantMembershipForRuntimeResponse.newBuilder() @@ -432,6 +525,16 @@ public void getTenantMembershipForRuntime( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (RuntimeException ex) { + responseObserver.onNext( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setError( + appError( + "GetTenantMembershipForRuntime", + "AUTH_UNAVAILABLE", + AUTHORITY_UNAVAILABLE_MESSAGE)) + .build()); + responseObserver.onCompleted(); } } @@ -441,25 +544,48 @@ public void getRealmAccessGrantForRuntime( GetRealmAccessGrantForRuntimeRequest request, StreamObserver responseObserver) { try { + requireGameSessionPeer(); + UUID accountUuid = requireCanonicalAccountUuid(request.getAccountId()); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + String worldSlug = requireText(request.getWorldSlug(), "worldSlug"); + String realmSlug = requireText(request.getRealmSlug(), "realmSlug"); + long accountStorageId = accountService.resolveAccountStorageId(accountUuid); var dto = accountService.getRealmAccessGrantForRuntime( - requirePositiveRequestId(request.getAccountId(), "accountId"), - requirePositiveRequestId(request.getTenantId(), "tenantId"), - request.getWorldSlug(), - request.getRealmSlug(), - request.getRequestId()); + accountStorageId, + tenantId, + worldSlug, + realmSlug, + requireText(request.getRequestId(), "requestId")); + if (dto.accountId() != accountStorageId + || dto.tenantId() != tenantId + || !worldSlug.equals(dto.worldSlug()) + || !realmSlug.equals(dto.realmSlug()) + || (dto.granted() && dto.grantVersion() <= 0L) + || dto.evaluatedAt() == null + || dto.evaluatedAt().isBlank() + || Instant.parse(dto.evaluatedAt()).isAfter(Instant.now().plusSeconds(5))) { + throw new IllegalStateException("Account returned mismatched realm-grant authority"); + } GetRealmAccessGrantForRuntimeResponse response = GetRealmAccessGrantForRuntimeResponse.newBuilder() - .setAccountId(String.valueOf(dto.accountId())) - .setTenantId(String.valueOf(dto.tenantId())) - .setWorldSlug(dto.worldSlug()) - .setRealmSlug(dto.realmSlug()) + .setAccountId(accountUuid.toString()) + .setTenantId(Long.toString(tenantId)) + .setWorldSlug(worldSlug) + .setRealmSlug(realmSlug) .setGranted(dto.granted()) .setGrantVersion(dto.grantVersion()) .setEvaluatedAt(dto.evaluatedAt()) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setError( + appError("GetRealmAccessGrantForRuntime", "PERMISSION_DENIED", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { GetRealmAccessGrantForRuntimeResponse response = GetRealmAccessGrantForRuntimeResponse.newBuilder() @@ -475,6 +601,16 @@ public void getRealmAccessGrantForRuntime( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (RuntimeException ex) { + responseObserver.onNext( + GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setError( + appError( + "GetRealmAccessGrantForRuntime", + "AUTH_UNAVAILABLE", + AUTHORITY_UNAVAILABLE_MESSAGE)) + .build()); + responseObserver.onCompleted(); } } @@ -484,9 +620,10 @@ public void getTenantEntitlementsForRuntime( GetTenantEntitlementsForRuntimeRequest request, StreamObserver responseObserver) { try { - var dto = - accountService.getTenantEntitlementsForRuntime( - requirePositiveRequestId(request.getTenantId(), "tenantId"), request.getRequestId()); + requireRuntimeEntitlementsPeer(); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + String requestId = requireText(request.getRequestId(), "requestId"); + var dto = accountService.getTenantEntitlementsForRuntime(tenantId, requestId); GetTenantEntitlementsForRuntimeResponse response = GetTenantEntitlementsForRuntimeResponse.newBuilder() .setTenantId(String.valueOf(dto.tenantId())) @@ -498,6 +635,14 @@ public void getTenantEntitlementsForRuntime( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + GetTenantEntitlementsForRuntimeResponse response = + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setError( + appError("GetTenantEntitlementsForRuntime", "PERMISSION_DENIED", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { GetTenantEntitlementsForRuntimeResponse response = GetTenantEntitlementsForRuntimeResponse.newBuilder() @@ -528,16 +673,29 @@ public void getTenantEntitlementsForRuntime( public void getProfile( GetProfileRequest request, StreamObserver responseObserver) { try { - var dto = - accountService.getProfile( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - requirePositiveRequestId(request.getAccountId(), "accountId")); + requireSocialGroupsPeer(); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + UUID accountUuid = requireCanonicalAccountUuid(request.getAccountId()); + requireCallerAccountSubject(accountUuid); + long accountId = accountService.resolveAccountStorageId(accountUuid); + var dto = accountService.getProfile(tenantId, accountId); + if (dto == null + || !accountUuid.toString().equals(dto.accountId()) + || !Long.valueOf(tenantId).equals(dto.tenantId())) { + throw new IllegalStateException("Profile authority returned a different owner"); + } GetProfileResponse response = GetProfileResponse.newBuilder() .setProfileJson(JsonMapper.builder().build().writeValueAsString(dto)) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + GetProfileResponse.newBuilder() + .setError(appError("GetProfile", "PERMISSION_DENIED", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { GetProfileResponse response = GetProfileResponse.newBuilder() @@ -552,6 +710,12 @@ public void getProfile( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (RuntimeException ignored) { + responseObserver.onNext( + GetProfileResponse.newBuilder() + .setError(appError("GetProfile", "AUTH_UNAVAILABLE", AUTHORITY_UNAVAILABLE_MESSAGE)) + .build()); + responseObserver.onCompleted(); } } @@ -562,29 +726,67 @@ public void listPresenceVisibilityPolicies( StreamObserver responseObserver) { try { + requireSocialGroupsPeer(); long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); if (request.getAccountIdsCount() > MAX_ACCOUNT_IDS_PER_REQUEST) { throw new InvalidRequestException( "accountIds must contain at most " + MAX_ACCOUNT_IDS_PER_REQUEST + " entries", null); } - java.util.List accountIds = + java.util.List accountUuids = request.getAccountIdsList().stream() - .map(accountId -> requirePositiveRequestId(accountId, "accountId")) + .map(AccountGrpcService::requireCanonicalAccountUuid) .distinct() .toList(); + java.util.Map storageIdsByAccountUuid = new java.util.LinkedHashMap<>(); + java.util.Map accountUuidsByStorageId = new java.util.HashMap<>(); + for (UUID accountUuid : accountUuids) { + Long storageId; + try { + storageId = accountService.resolveAccountStorageId(accountUuid); + } catch (IllegalArgumentException | IllegalStateException ex) { + // Unknown or unproven local subjects are omitted so Social applies complete PRIVATE + // redaction rather than receiving a guessed identity or a private storage key. + continue; + } + if (storageId == null || storageId <= 0L) { + continue; + } + UUID previousAccountUuid = accountUuidsByStorageId.putIfAbsent(storageId, accountUuid); + if (previousAccountUuid != null && !previousAccountUuid.equals(accountUuid)) { + throw new IllegalStateException("Account UUID resolution returned an ambiguous row"); + } + storageIdsByAccountUuid.put(accountUuid, storageId); + } + java.util.List storageIds = java.util.List.copyOf(storageIdsByAccountUuid.values()); + java.util.Map policies = + storageIds.isEmpty() + ? java.util.Map.of() + : accountService.listPresenceVisibilityPolicies(tenantId, storageIds); + for (java.util.Map.Entry policy : + policies.entrySet()) { + if (!accountUuidsByStorageId.containsKey(policy.getKey()) || policy.getValue() == null) { + throw new IllegalStateException( + "Presence visibility policy read returned an unexpected Account row"); + } + } var builder = net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse.newBuilder(); - accountService - .listPresenceVisibilityPolicies(tenantId, accountIds) - .forEach( - (accountId, policy) -> - builder.addPolicies( - net.firedevops.firemud.account.v1.PresenceVisibilityPolicyEntry.newBuilder() - .setAccountId(Long.toString(accountId)) - .setPolicy(policy.name()) - .build())); + policies.forEach( + (storageId, policy) -> + builder.addPolicies( + net.firedevops.firemud.account.v1.PresenceVisibilityPolicyEntry.newBuilder() + .setAccountId(accountUuidsByStorageId.get(storageId).toString()) + .setPolicy(policy.name()) + .build())); responseObserver.onNext(builder.build()); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse.newBuilder() + .setError( + appError("ListPresenceVisibilityPolicies", "PERMISSION_DENIED", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { responseObserver.onNext( net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse.newBuilder() @@ -601,7 +803,11 @@ public void listPresenceVisibilityPolicies( } catch (RuntimeException ex) { responseObserver.onNext( net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse.newBuilder() - .setError(appError("ListPresenceVisibilityPolicies", "INTERNAL", ex.getMessage())) + .setError( + appError( + "ListPresenceVisibilityPolicies", + "INTERNAL", + "Presence visibility policy lookup failed")) .build()); responseObserver.onCompleted(); } @@ -612,23 +818,59 @@ public void listPresenceVisibilityPolicies( public void updateProfile( UpdateProfileRequest request, StreamObserver responseObserver) { try { - JsonNode node = JsonMapper.builder().build().readTree(request.getProfileJson()); + requireSocialGroupsPeer(); + long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + UUID accountUuid = requireCanonicalAccountUuid(request.getAccountId()); + requireCallerAccountSubject(accountUuid); + try { + accountService.resolveAccountStorageId(accountUuid); + } catch (IllegalArgumentException ex) { + responseObserver.onNext( + UpdateProfileResponse.newBuilder() + .setSuccess(false) + .setError(appError("UpdateProfile", "NOT_FOUND", ex.getMessage())) + .build()); + responseObserver.onCompleted(); + return; + } + JsonNode node; + ProfilePresenceVisibilityPolicy policy; + try { + node = JsonMapper.builder().build().readTree(request.getProfileJson()); + if (node == null || !node.isObject()) { + throw new IllegalArgumentException("Profile update must be an object"); + } + String policyName = node.path("presenceVisibilityPolicy").asText(null); + policy = + ProfilePresenceVisibilityPolicy.valueOf( + policyName == null + ? ProfilePresenceVisibilityPolicy.FRIENDS_ONLY.name() + : policyName); + } catch (JacksonException | IllegalArgumentException ex) { + throw new InvalidRequestException("profileJson must contain a valid profile update", ex); + } String displayName = node.path("displayName").asText(null); String bio = node.path("bio").asText(null); - String presenceVisibilityPolicy = node.path("presenceVisibilityPolicy").asText(null); - accountService.updateProfile( - new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - requirePositiveRequestId(request.getAccountId(), "accountId"), - displayName, - bio, - ProfilePresenceVisibilityPolicy.valueOf( - presenceVisibilityPolicy == null - ? ProfilePresenceVisibilityPolicy.FRIENDS_ONLY.name() - : presenceVisibilityPolicy))); + var dto = + accountService.updateProfile( + new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( + tenantId, accountUuid.toString(), displayName, bio, policy)); + if (dto == null + || !accountUuid.toString().equals(dto.accountId()) + || !Long.valueOf(tenantId).equals(dto.tenantId())) { + throw new IllegalStateException("Profile authority returned a different owner"); + } UpdateProfileResponse response = UpdateProfileResponse.newBuilder().setSuccess(true).build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + UpdateProfileResponse response = + UpdateProfileResponse.newBuilder() + .setSuccess(false) + .setError(appError("UpdateProfile", "PERMISSION_DENIED", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { UpdateProfileResponse response = UpdateProfileResponse.newBuilder() @@ -637,7 +879,7 @@ public void updateProfile( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); - } catch (Exception ex) { + } catch (IllegalArgumentException ex) { UpdateProfileResponse response = UpdateProfileResponse.newBuilder() .setSuccess(false) @@ -645,6 +887,14 @@ public void updateProfile( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (RuntimeException ignored) { + responseObserver.onNext( + UpdateProfileResponse.newBuilder() + .setSuccess(false) + .setError( + appError("UpdateProfile", "AUTH_UNAVAILABLE", AUTHORITY_UNAVAILABLE_MESSAGE)) + .build()); + responseObserver.onCompleted(); } } @@ -655,7 +905,8 @@ public void exportAccount( try { var data = accountService.exportAccountData( - requirePositiveRequestId(request.getAccountId(), "accountId")); + accountService.resolveAccountStorageId( + requireCanonicalAccountUuid(request.getAccountId()))); ExportAccountResponse response = ExportAccountResponse.newBuilder() .setAccountJson(JsonMapper.builder().build().writeValueAsString(data.account())) @@ -688,7 +939,8 @@ public void exportTenantData( var data = accountService.exportTenantData( requirePositiveRequestId(request.getTenantId(), "tenantId"), - requirePositiveRequestId(request.getAccountId(), "accountId")); + accountService.resolveAccountStorageId( + requireCanonicalAccountUuid(request.getAccountId()))); ExportTenantDataResponse response = ExportTenantDataResponse.newBuilder() .setTenantId(String.valueOf(data.tenantId())) @@ -723,7 +975,9 @@ public void deleteAccount( DeleteAccountRequest request, StreamObserver responseObserver) { try { AdminRoleGuard.requireAdminRole(); - accountService.deleteAccount(requirePositiveRequestId(request.getAccountId(), "accountId")); + accountService.deleteAccount( + accountService.resolveAccountStorageId( + requireCanonicalAccountUuid(request.getAccountId()))); DeleteAccountResponse response = DeleteAccountResponse.newBuilder().setSuccess(true).build(); responseObserver.onNext(response); responseObserver.onCompleted(); @@ -834,7 +1088,8 @@ public void linkExternalAccount( accountService.linkExternalAccount( new net.firedevops.firemud.accountservice.dto.LinkExternalAccountRequest( requirePositiveRequestId(request.getTenantId(), "tenantId"), - requirePositiveRequestId(request.getAccountId(), "accountId"), + accountService.resolveAccountStorageId( + requireCanonicalAccountUuid(request.getAccountId())), request.getProvider(), request.getExternalId())); var response = @@ -870,7 +1125,8 @@ public void requestEmailVerification( responseObserver) { try { accountService.requestEmailVerification( - requirePositiveRequestId(request.getAccountId(), "accountId")); + accountService.resolveAccountStorageId( + requireCanonicalAccountUuid(request.getAccountId()))); var response = net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() .setSuccess(true) 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 4d4f6d2ba6..58bd605806 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 @@ -22,6 +22,7 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.accountservice.AccountUuidText; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.config.AccountTokenProperties; @@ -298,16 +299,16 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult authentica String username, String password) { PrimaryAuthentication authentication = authenticateAccountIdentity(username, password, true); Account account = authentication.account(); + String accountUuid = requireAuthenticationAccountUuid(account).toString(); authentication.emailLoginChallenge().ifPresent(accountEmailLoginChallengeRepository::delete); String token = mintToken( - account.getId().toString(), + accountUuid, jwtAuthProperties.getJwtExpirationMs(), authenticationTokenClaims("control-ui", account)); sessionService.storeAccountSession( account.getId(), token, jwtAuthProperties.getJwtExpirationMs()); - return new net.firedevops.firemud.accountservice.dto.AuthenticationResult( - account.getId(), token); + return new net.firedevops.firemud.accountservice.dto.AuthenticationResult(accountUuid, token); } @Override @@ -322,16 +323,16 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult authentica PrimaryAuthentication authentication = authenticateAccountIdentity(gameplayAccount, password, true); Account account = authentication.account(); + String accountUuid = requireAuthenticationAccountUuid(account).toString(); authentication.emailLoginChallenge().ifPresent(accountEmailLoginChallengeRepository::delete); String token = mintToken( - account.getId().toString(), + accountUuid, jwtAuthProperties.getJwtExpirationMs(), authenticationTokenClaims(GAMEPLAY_DELEGATION_AUDIENCE, account)); sessionService.storeAccountSession( account.getId(), token, jwtAuthProperties.getJwtExpirationMs()); - return new net.firedevops.firemud.accountservice.dto.AuthenticationResult( - account.getId(), token); + return new net.firedevops.firemud.accountservice.dto.AuthenticationResult(accountUuid, token); } @Override @@ -396,16 +397,16 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult verifyEmai throw invalidCredentials(); } requireAuthenticationEligible(account); + String accountUuid = requireAuthenticationAccountUuid(account).toString(); accountEmailLoginChallengeRepository.delete(challenge); String token = mintToken( - account.getId().toString(), + accountUuid, jwtAuthProperties.getJwtExpirationMs(), authenticationTokenClaims(GAMEPLAY_DELEGATION_AUDIENCE, account)); sessionService.storeAccountSession( account.getId(), token, jwtAuthProperties.getJwtExpirationMs()); - return new net.firedevops.firemud.accountservice.dto.AuthenticationResult( - account.getId(), token); + return new net.firedevops.firemud.accountservice.dto.AuthenticationResult(accountUuid, token); } @Override @@ -415,20 +416,21 @@ public PlayerBootstrapResult issuePlayerBootstrap(String accountIdentifier, Stri PrimaryAuthentication authentication = authenticateAccountIdentity(accountIdentifier, secret, true); Account account = authentication.account(); + String accountUuid = requireAuthenticationAccountUuid(account).toString(); authentication.emailLoginChallenge().ifPresent(accountEmailLoginChallengeRepository::delete); String jti = UUID.randomUUID().toString(); long issuedAt = System.currentTimeMillis(); long expiresAt = issuedAt + tokenProperties.getPlayerBootstrapExpirationMs(); String bootstrapToken = mintToken( - String.valueOf(account.getId()), + accountUuid, tokenProperties.getPlayerBootstrapExpirationMs(), - Map.of("aud", "player-bootstrap", "accountId", account.getId(), "jti", jti)); + Map.of("aud", "player-bootstrap", "accountId", accountUuid, "jti", jti)); sessionService.storeAccountSession( account.getId(), bootstrapToken, tokenProperties.getPlayerBootstrapExpirationMs()); logger.info("Issued player bootstrap token for account {}", account.getId()); return new PlayerBootstrapResult( - account.getId(), + accountUuid, bootstrapToken, Instant.ofEpochMilli(issuedAt).toString(), Instant.ofEpochMilli(expiresAt).toString()); @@ -595,7 +597,12 @@ public DirectTextJoinScope issueDirectTextConnectScope( Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); String scopeId = mintAndRetainConnectScope( - new BootstrapContext(caller.accountId()), current, evaluatedAt, expiresAt); + new BootstrapContext( + caller.accountId(), + requireAuthenticationAccountUuid(requireAccount(caller.accountId())).toString()), + current, + evaluatedAt, + expiresAt); return new DirectTextJoinScope(scopeId, expiresAt.toString()); } @@ -1294,12 +1301,15 @@ private BootstrapContext requireBootstrapContext(String bootstrapToken) { "Missing bootstrap token", "Invalid bootstrap token"); try { - long accountId = requireSignedActorAccountId(claims); + String accountUuid = + JwtClaims.requireSignedGameplayAccountUuid( + claims, "signed token account subject mismatch"); + long accountId = resolveAccountStorageId(UUID.fromString(accountUuid)); if (!sessionService.isAccountSessionActive(accountId, bootstrapToken)) { throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Bootstrap token expired"); } - return new BootstrapContext(accountId); - } catch (IllegalArgumentException ex) { + return new BootstrapContext(accountId, accountUuid); + } catch (IllegalArgumentException | IllegalStateException ex) { throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Invalid bootstrap token", ex); } } @@ -1534,11 +1544,11 @@ private String mintConnectScopeId( Instant expiresAt) { long expirationMs = Math.max(1L, expiresAt.toEpochMilli() - evaluatedAt.toEpochMilli()); return mintToken( - String.valueOf(bootstrapContext.accountId()), + bootstrapContext.accountUuid(), expirationMs, Map.ofEntries( Map.entry("aud", "bootstrap-connect-scope"), - Map.entry("accountId", bootstrapContext.accountId()), + Map.entry("accountId", bootstrapContext.accountUuid()), Map.entry("tenantId", realm.tenantId()), Map.entry("realmId", realm.realmId().toString()), Map.entry("worldSlug", realm.worldSlug()), @@ -1622,8 +1632,9 @@ private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { if (evaluatedAt == null) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); } + long accountId = resolveAccountStorageId(UUID.fromString(routingClaims.accountId())); return new ConnectScopeContext( - routingClaims.accountId(), + accountId, routingClaims.tenantId(), requireCanonicalRealmId(claims.get("realmId")), routingClaims.worldSlug(), @@ -1635,15 +1646,11 @@ private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { routingClaims.pointerVersion(), evaluatedAt, connectScopeExpiresAt); - } catch (IllegalArgumentException ex) { + } catch (IllegalArgumentException | IllegalStateException ex) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE, ex); } } - private static long requireSignedActorAccountId(Claims claims) { - return JwtClaims.requireSignedActorAccountId(claims, "signed token account subject mismatch"); - } - private Claims requireSignedTokenClaims( String token, String expectedAudience, @@ -2033,6 +2040,20 @@ private Account requireAccount(Long accountId) { .orElseThrow(() -> new IllegalArgumentException("Account not found")); } + private UUID requireAuthenticationAccountUuid(Account account) { + requireAuthenticationPersistedIdentity(account); + UUID accountUuid = account.getAccountUuid(); + try { + Long storageId = resolveAccountStorageId(accountUuid); + if (!Objects.equals(account.getId(), storageId)) { + throw new IllegalStateException("Account identity does not match its persisted owner"); + } + } catch (IllegalArgumentException | IllegalStateException ex) { + throw new IllegalStateException("Account identity does not match its persisted owner", ex); + } + return accountUuid; + } + /** Resolves a canonical public identity at the Account persistence boundary only. */ @Override @Transactional(readOnly = true) @@ -2080,7 +2101,7 @@ private Map authenticationTokenClaims(String audience, Account a "aud", audience, "accountId", - account.getId(), + account.getAccountUuid().toString(), "globalRoles", globalRoles, "jti", @@ -2146,7 +2167,7 @@ public ProfileDto getProfile(Long tenantId, Long accountId) { profileRepository .findByAccountIdAndTenantId(accountId, tenantId) .orElseThrow(() -> new IllegalArgumentException("Profile not found")); - return profileMapper.toDto(profile); + return projectProfile(profile, tenantId, accountId); } @Override @@ -2175,20 +2196,50 @@ public Map listPresenceVisibilityPolicies @Timed(value = "account.update_profile") public ProfileDto updateProfile(UpdateProfileRequest request) { request.presenceVisibilityPolicy().requireSelectableByAccountHolder(); - requireProfileMembership(request.tenantId(), request.accountId()); + UUID accountUuid = AccountUuidText.parseOrNull(request.accountId()); + if (accountUuid == null) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + Long accountId = resolveAccountStorageId(accountUuid); + requireProfileMembership(request.tenantId(), accountId); Profile profile = profileRepository - .findByAccountIdAndTenantId(request.accountId(), request.tenantId()) + .findByAccountIdAndTenantId(accountId, request.tenantId()) .orElseThrow(() -> new IllegalArgumentException("Profile not found")); + requireProfileOwner(profile, request.tenantId(), accountId); profile.setDisplayName(request.displayName()); profile.setBio(request.bio()); profile.setPresenceVisibilityPolicy(request.presenceVisibilityPolicy()); profile = profileRepository.save(profile); runAfterCommit( () -> - notificationService.sendNotification( - request.tenantId(), request.accountId(), "Profile updated")); - return profileMapper.toDto(profile); + notificationService.sendNotification(request.tenantId(), accountId, "Profile updated")); + return projectProfile(profile, request.tenantId(), accountId); + } + + private static void requireProfileOwner(Profile profile, Long tenantId, Long accountId) { + if (profile == null + || profile.getAccount() == null + || !Objects.equals(profile.getAccount().getId(), accountId) + || !Objects.equals(profile.getTenantId(), tenantId)) { + throw new IllegalStateException("Profile does not match its requested owner"); + } + } + + private ProfileDto projectProfile(Profile profile, Long tenantId, Long accountId) { + requireProfileOwner(profile, tenantId, accountId); + Account account = requireAccount(accountId); + if (!Objects.equals(account.getId(), accountId)) { + throw new IllegalStateException("Profile Account readback returned a different owner"); + } + String accountUuid = requireAuthenticationAccountUuid(account).toString(); + ProfileDto dto = profileMapper.toDto(profile, accountUuid); + if (dto == null + || !accountUuid.equals(dto.accountId()) + || !Objects.equals(tenantId, dto.tenantId())) { + throw new IllegalStateException("Profile projection does not match its persisted owner"); + } + return dto; } private void requireProfileMembership(Long tenantId, Long accountId) { @@ -2221,7 +2272,9 @@ public AccountLoginAuthModesDto updateLoginAuthModes( public AccountDataExportDto exportAccountData(Long accountId) { Account account = requireAccount(accountId); List profiles = - profileRepository.findByAccountId(accountId).stream().map(profileMapper::toDto).toList(); + profileRepository.findByAccountId(accountId).stream() + .map(profile -> projectProfile(profile, profile.getTenantId(), accountId)) + .toList(); return new AccountDataExportDto(accountMapper.toDto(account), profiles); } @@ -2239,7 +2292,7 @@ public TenantDataExportDto exportTenantData(Long tenantId, Long accountId) { return new TenantDataExportDto( tenantId, accountMapper.toDto(account), - profile != null ? profileMapper.toDto(profile) : null); + profile != null ? projectProfile(profile, tenantId, accountId) : null); } @Override @@ -3153,7 +3206,7 @@ public void afterCommit() { }); } - private record BootstrapContext(long accountId) {} + private record BootstrapContext(long accountId, String accountUuid) {} private record JoinAuditPayload( long accountId, diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index b51fe45e89..138a962cd0 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -72,6 +72,8 @@ firemud: - account.v1.AccountService/RequestEmailLoginOtp - account.v1.AccountService/VerifyEmailLoginOtp - account.v1.AccountService/Ping + - account.v1.AccountService/ListPresenceVisibilityPolicies + - account.v1.AccountService/GetRealmAccessGrantForRuntime - account.v1.AccountService/GetTenantMembershipForRuntime - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 1af06e52a7..790568480b 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -104,6 +104,8 @@ firemud: - account.v1.AccountService/RequestEmailLoginOtp - account.v1.AccountService/VerifyEmailLoginOtp - account.v1.AccountService/Ping + - account.v1.AccountService/ListPresenceVisibilityPolicies + - account.v1.AccountService/GetRealmAccessGrantForRuntime - account.v1.AccountService/GetTenantMembershipForRuntime - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 620742cab5..3d8cdc7805 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -114,14 +114,19 @@ components: type: object properties: accountId: - type: integer + type: string + format: uuid + description: Canonical non-nil Account UUID read back from the authenticated source row; never the numeric database primary key. authToken: type: string + required: [accountId, authToken] PlayerBootstrapResult: type: object properties: accountId: - type: integer + type: string + format: uuid + description: Canonical non-nil Account UUID; never the private numeric database primary key. bootstrapToken: type: string issuedAt: @@ -237,6 +242,8 @@ components: type: string accountId: type: string + format: uuid + description: Canonical non-nil Account UUID; never a private database row ID. displayName: type: string bio: @@ -248,6 +255,8 @@ components: type: string accountId: type: string + format: uuid + description: Canonical non-nil Account UUID; never a private database row ID. displayName: type: string bio: @@ -630,7 +639,8 @@ paths: in: path required: true schema: - type: integer + type: string + format: uuid responses: '200': description: Exported data @@ -646,6 +656,7 @@ paths: required: true schema: type: string + format: uuid responses: '200': description: Allowed login mechanisms @@ -666,6 +677,7 @@ paths: required: true schema: type: string + format: uuid requestBody: required: true content: @@ -688,7 +700,8 @@ paths: in: path required: true schema: - type: integer + type: string + format: uuid - name: tenantId in: query required: true @@ -708,7 +721,8 @@ paths: in: path required: true schema: - type: integer + type: string + format: uuid responses: '200': description: Deletion success @@ -723,7 +737,8 @@ paths: in: path required: true schema: - type: integer + type: string + format: uuid - name: tenantId in: query required: true @@ -746,7 +761,8 @@ paths: in: path required: true schema: - type: integer + type: string + format: uuid requestBody: required: true content: diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index a3a6d0602a..aa8daa9904 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -159,6 +159,90 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws assertThat(tenantExport.profile()).isNull(); } + @Test + void ordinaryAuthenticationReturnsPersistedAccountUuidInResponseAndValidatedJwt() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String username = "auth-uuid-" + suffix; + String email = username + "@example.com"; + HttpRequest registrationRequest = + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/accounts")) + .header(HttpHeaders.CONTENT_TYPE, "application/json") + .POST( + HttpRequest.BodyPublishers.ofString( + "{\"username\":\"" + + username + + "\",\"email\":\"" + + email + + "\",\"password\":\"password123\"}")) + .build(); + + HttpResponse registrationResponse = + HTTP_CLIENT.send(registrationRequest, HttpResponse.BodyHandlers.ofString()); + + assertThat(registrationResponse.statusCode()).isEqualTo(200); + Number accountId = + dsl.resultQuery("SELECT id FROM accounts WHERE email = ?", email).fetchOne(0, Number.class); + assertThat(accountId).isNotNull(); + long numericAccountId = accountId.longValue(); + UUID persistedAccountUuid = + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", numericAccountId) + .fetchOne(0, UUID.class); + Long sourceNumericId = + dsl.resultQuery( + "SELECT account_uuid_source_numeric_id FROM accounts WHERE id = ?", + numericAccountId) + .fetchOne(0, Long.class); + String provenance = + dsl.resultQuery( + "SELECT account_uuid_provenance FROM accounts WHERE id = ?", numericAccountId) + .fetchOne(0, String.class); + assertThat(persistedAccountUuid).isNotNull(); + assertThat(jsonMapper.readTree(registrationResponse.body()).path("data").path("id").asText()) + .isEqualTo(persistedAccountUuid.toString()); + assertThat(sourceNumericId).isEqualTo(numericAccountId); + assertThat(provenance).isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + + HttpRequest authenticationRequest = + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/auth/login")) + .header(HttpHeaders.CONTENT_TYPE, "application/json") + .POST( + HttpRequest.BodyPublishers.ofString( + "{\"username\":\"" + + username + + "\",\"password\":\"password123\"}")) + .build(); + + HttpResponse authenticationResponse = + HTTP_CLIENT.send(authenticationRequest, HttpResponse.BodyHandlers.ofString()); + + assertThat(authenticationResponse.statusCode()).isEqualTo(200); + var data = jsonMapper.readTree(authenticationResponse.body()).path("data"); + assertThat(data.path("accountId").asText()).isEqualTo(persistedAccountUuid.toString()); + String token = data.path("authToken").asText(); + assertThat(token).isNotBlank(); + var claims = jwtUtil.parseToken(token).getPayload(); + assertThat(claims.getSubject()).isEqualTo(persistedAccountUuid.toString()); + assertThat(claims.get("accountId", String.class)).isEqualTo(persistedAccountUuid.toString()); + assertThat(authenticationResponse.body()) + .doesNotContain("\"accountId\":" + numericAccountId); + + assertThat( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", numericAccountId) + .fetchOne(0, UUID.class)) + .isEqualTo(persistedAccountUuid); + assertThat( + dsl.resultQuery( + "SELECT account_uuid_source_numeric_id FROM accounts WHERE id = ?", + numericAccountId) + .fetchOne(0, Long.class)) + .isEqualTo(sourceNumericId); + assertThat( + dsl.resultQuery( + "SELECT account_uuid_provenance FROM accounts WHERE id = ?", numericAccountId) + .fetchOne(0, String.class)) + .isEqualTo(provenance); + } + @Test void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws Exception { String token = @@ -166,7 +250,7 @@ void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws "operator", java.util.Map.of("globalRoles", java.util.List.of("platformAdmin"))); HttpRequest request = HttpRequest.newBuilder( - URI.create("http://localhost:" + port + "/accounts/not-a-number/export")) + URI.create("http://localhost:" + port + "/accounts/not-a-uuid/export")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .GET() .build(); @@ -175,12 +259,14 @@ void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws assertThat(response.statusCode()).isEqualTo(400); assertThat(response.body()).contains("\"code\":\"INVALID_ARGUMENT\""); - assertThat(response.body()).contains("\"message\":\"accountId must be numeric\""); + assertThat(response.body()) + .contains("\"message\":\"accountId must be a canonical non-nil UUID\""); } @Test void linkExternalRouteIsUnavailableWithAuthenticatedRequest() throws Exception { - String token = jwtUtil.generateToken("2", java.util.Map.of("accountId", "2")); + String accountUuid = "6bb95a5e-3b0a-4eac-85d0-5c1b83467ad2"; + String token = jwtUtil.generateToken(accountUuid, java.util.Map.of("accountId", accountUuid)); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/accounts/2/external")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -201,9 +287,10 @@ void linkExternalRouteIsUnavailableWithAuthenticatedRequest() throws Exception { @Test void updateProfileRejectsZeroTenantIdWithInvalidArgumentEnvelope() throws Exception { - String token = jwtUtil.generateToken("2", java.util.Map.of("accountId", "2")); + String accountUuid = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + String token = jwtUtil.generateToken(accountUuid, java.util.Map.of("accountId", accountUuid)); HttpRequest request = - HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/profiles/2")) + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/profiles/" + accountUuid)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .header(HttpHeaders.CONTENT_TYPE, "application/json") .PUT( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java index 616ff0fbc1..1c9c811d5c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java @@ -52,6 +52,8 @@ "firemud.auth.http.public-routes[1].path-pattern=/accounts/" }) class AccountControllerTest { + private static final String ACCOUNT_UUID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + private static final String OTHER_ACCOUNT_UUID = "a2e1342e-a139-49c6-a460-c8e25f6697ae"; @Autowired private MockMvc mockMvc; private final ObjectMapper objectMapper = new ObjectMapper(); @@ -115,11 +117,18 @@ void createAccountRetainsMinimumPasswordLength() throws Exception { } @Test - void deleteAccountAllowsScopedTenantAdmin() throws Exception { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + void deleteAccountAllowsGlobalAdmin() throws Exception { + String token = + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); + when(accountService.resolveAccountStorageId(java.util.UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); mockMvc - .perform(delete("/accounts/42").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .perform( + delete("/accounts/" + ACCOUNT_UUID) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")); } @@ -127,10 +136,18 @@ void deleteAccountAllowsScopedTenantAdmin() throws Exception { @Test void deleteAccountRejectsScopedTenantAdminBecauseFullDeletionIsAccountScoped() throws Exception { String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("7", List.of("tenantAdmin")))); + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of( + "accountId", + OTHER_ACCOUNT_UUID, + "scopedRoles", + Map.of("7", List.of("tenantAdmin")))); mockMvc - .perform(delete("/accounts/42").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .perform( + delete("/accounts/" + ACCOUNT_UUID) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isForbidden()) .andExpect(jsonPath("$.error.code").value("PERMISSION_DENIED")) .andExpect(jsonPath("$.error.message").value("Account access required")); @@ -143,10 +160,14 @@ void exportAccountAllowsCurrentAccountWithoutTenantScope() throws Exception { "4cae05e8-7a6b-4b14-9d44-665e3eec450b", "demo", "demo@example.com", "player", true); when(accountService.exportAccountData(42L)) .thenReturn(new AccountDataExportDto(account, List.of())); - String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); + when(accountService.resolveAccountStorageId(java.util.UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc - .perform(get("/accounts/42/export").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .perform( + get("/accounts/" + ACCOUNT_UUID + "/export") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")); } @@ -158,12 +179,17 @@ void exportTenantDataAllowsScopedTenantRole() throws Exception { "4cae05e8-7a6b-4b14-9d44-665e3eec450b", "demo", "demo@example.com", "player", true); when(accountService.exportTenantData(7L, 42L)) .thenReturn(new TenantDataExportDto(7L, account, null)); + when(accountService.resolveAccountStorageId(java.util.UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("7", List.of("moderator")))); + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of( + "accountId", OTHER_ACCOUNT_UUID, "scopedRoles", Map.of("7", List.of("moderator")))); mockMvc .perform( - get("/accounts/42/tenant-export") + get("/accounts/" + ACCOUNT_UUID + "/tenant-export") .param("tenantId", "7") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) @@ -172,26 +198,31 @@ void exportTenantDataAllowsScopedTenantRole() throws Exception { @Test void exportAccountRejectsMalformedAccountIdBeforeDispatch() throws Exception { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( - get("/accounts/not-a-number/export") - .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + get("/accounts/not-a-uuid/export").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("accountId must be numeric")); + .andExpect(jsonPath("$.error.message").value("accountId must be a canonical non-nil UUID")); verifyNoInteractions(accountService); } @Test void exportTenantDataRejectsZeroTenantIdBeforeDispatch() throws Exception { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( - get("/accounts/42/tenant-export") + get("/accounts/" + ACCOUNT_UUID + "/tenant-export") .param("tenantId", "0") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) @@ -203,11 +234,13 @@ void exportTenantDataRejectsZeroTenantIdBeforeDispatch() throws Exception { @Test void deleteAccountAllowsCurrentAccountWithoutPrivilegedTenantRole() throws Exception { - String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); + when(accountService.resolveAccountStorageId(java.util.UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - delete("/accounts/42") + delete("/accounts/" + ACCOUNT_UUID) .param("tenantId", "7") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) @@ -215,21 +248,23 @@ void deleteAccountAllowsCurrentAccountWithoutPrivilegedTenantRole() throws Excep } @Test - void deleteAccountRejectsZeroAccountIdBeforeDispatch() throws Exception { - String token = jwtUtil.generateToken("1", Map.of("accountId", "1")); + void deleteAccountRejectsNumericAccountIdBeforeDispatch() throws Exception { + String token = + jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("accountId", OTHER_ACCOUNT_UUID)); mockMvc .perform(delete("/accounts/0").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("accountId must be positive")); + .andExpect(jsonPath("$.error.message").value("accountId must be a canonical non-nil UUID")); verifyNoInteractions(accountService); } @Test void linkExternalRouteIsUnavailableForAuthenticatedRequest() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String token = + jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("accountId", OTHER_ACCOUNT_UUID)); mockMvc .perform( @@ -248,18 +283,20 @@ void loginAuthModesAllowCurrentAccountWithoutTenantScope() throws Exception { AccountLoginAuthModesDto modes = new AccountLoginAuthModesDto(java.util.Set.of(AccountLoginAuthMode.EMAIL_OTP)); when(accountService.getLoginAuthModes(42L)).thenReturn(modes); - String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); + when(accountService.resolveAccountStorageId(java.util.UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - get("/accounts/42/login-auth-modes") + get("/accounts/" + ACCOUNT_UUID + "/login-auth-modes") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.data.loginAuthModes[0]").value("EMAIL_OTP")); mockMvc .perform( - put("/accounts/42/login-auth-modes") + put("/accounts/" + ACCOUNT_UUID + "/login-auth-modes") .contentType(MediaType.APPLICATION_JSON) .content("{\"loginAuthModes\":[\"EMAIL_OTP\"]}") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -277,11 +314,13 @@ void loginAuthModesAllowCurrentAccountWithoutTenantScope() throws Exception { @Test void updateLoginAuthModesRejectsPlatformAdminBeforeDispatch() throws Exception { String token = - jwtUtil.generateToken("operator", Map.of("globalRoles", List.of("platformAdmin"))); + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( - put("/accounts/42/login-auth-modes") + put("/accounts/" + ACCOUNT_UUID + "/login-auth-modes") .contentType(MediaType.APPLICATION_JSON) .content("{\"loginAuthModes\":[\"PASSWORD\"]}") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -293,11 +332,11 @@ void updateLoginAuthModesRejectsPlatformAdminBeforeDispatch() throws Exception { @Test void updateLoginAuthModesRejectsEmptySetBeforeDispatch() throws Exception { - String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - put("/accounts/42/login-auth-modes") + put("/accounts/" + ACCOUNT_UUID + "/login-auth-modes") .contentType(MediaType.APPLICATION_JSON) .content("{\"loginAuthModes\":[]}") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java index 7a50923772..d0b3d6ce46 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java @@ -60,10 +60,18 @@ void publicOpenApiOmitsUnavailableBootstrapJoin() throws Exception { Map paths = (Map) document.get("paths"); Map components = (Map) document.get("components"); Map schemas = (Map) components.get("schemas"); + Map playerBootstrapResult = + (Map) schemas.get("PlayerBootstrapResult"); + Map playerBootstrapProperties = + (Map) playerBootstrapResult.get("properties"); + Map playerBootstrapAccountId = + (Map) playerBootstrapProperties.get("accountId"); assertFalse(paths.containsKey("/auth/bootstrap/join")); assertTrue(((Map) paths.get("/auth/player-bootstrap")).containsKey("post")); assertTrue(((Map) paths.get("/auth/connect-token")).containsKey("post")); + assertEquals("string", playerBootstrapAccountId.get("type")); + assertEquals("uuid", playerBootstrapAccountId.get("format")); assertFalse(schemas.containsKey("JoinPublicProductionRequest")); assertFalse(schemas.containsKey("JoinPublicProductionResult")); } @@ -89,7 +97,7 @@ void publicOpenApiDocumentsRetryableCharacterDiscoveryOutage() throws Exception void loginReturnsTokenAndAccountId() throws Exception { LoginRequest request = new LoginRequest("demo", "password"); when(accountService.authenticate("demo", "password")) - .thenReturn(new AuthenticationResult(1L, "tok123")); + .thenReturn(new AuthenticationResult("4cae05e8-7a6b-4b14-9d44-665e3eec450b", "tok123")); mockMvc .perform( @@ -98,7 +106,7 @@ void loginReturnsTokenAndAccountId() throws Exception { .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.accountId").value(1)) + .andExpect(jsonPath("$.data.accountId").value("4cae05e8-7a6b-4b14-9d44-665e3eec450b")) .andExpect(jsonPath("$.data.authToken").value("tok123")); } @@ -106,7 +114,7 @@ void loginReturnsTokenAndAccountId() throws Exception { void loginAcceptsExistingOneCharacterPassword() throws Exception { LoginRequest request = new LoginRequest("demo", "x"); when(accountService.authenticate("demo", "x")) - .thenReturn(new AuthenticationResult(1L, "tok123")); + .thenReturn(new AuthenticationResult("4cae05e8-7a6b-4b14-9d44-665e3eec450b", "tok123")); mockMvc .perform( @@ -124,7 +132,10 @@ void playerBootstrapReturnsShortLivedToken() throws Exception { when(accountService.issuePlayerBootstrap("demo", "password")) .thenReturn( new PlayerBootstrapResult( - 1L, "boot123", "2026-03-30T00:00:00Z", "2026-03-30T00:05:00Z")); + "4cae05e8-7a6b-4b14-9d44-665e3eec450b", + "boot123", + "2026-03-30T00:00:00Z", + "2026-03-30T00:05:00Z")); mockMvc .perform( @@ -133,7 +144,7 @@ void playerBootstrapReturnsShortLivedToken() throws Exception { .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.accountId").value(1)) + .andExpect(jsonPath("$.data.accountId").value("4cae05e8-7a6b-4b14-9d44-665e3eec450b")) .andExpect(jsonPath("$.data.bootstrapToken").value("boot123")); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java index 14b86c1fff..b33d343d5c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java @@ -33,6 +33,8 @@ @Import({CommonSecurityAutoConfiguration.class, CommonSecurityServletAutoConfiguration.class}) @WithFiremudHttpAuthTestProperties class ProfileControllerTest { + private static final String ACCOUNT_UUID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + private static final String OTHER_ACCOUNT_UUID = "a2e1342e-a139-49c6-a460-c8e25f6697ae"; @Autowired private MockMvc mockMvc; private final ObjectMapper objectMapper = new ObjectMapper(); @@ -48,32 +50,38 @@ void clear() { @Test void getProfileReturnsDto() throws Exception { ProfileDto dto = - new ProfileDto(1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); + new ProfileDto( + 1L, 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); when(accountService.getProfile(1L, 2L)).thenReturn(dto); + when(accountService.resolveAccountStorageId(java.util.UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - get("/profiles/2") + get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.displayName").value("demo")); + .andExpect(jsonPath("$.data.displayName").value("demo")) + .andExpect(jsonPath("$.data.accountId").value(ACCOUNT_UUID)); } @Test void updateProfileReturnsDto() throws Exception { UpdateProfileRequest req = - new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + new UpdateProfileRequest( + 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); ProfileDto dto = - new ProfileDto(1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + new ProfileDto( + 1L, 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); when(accountService.updateProfile(req)).thenReturn(dto); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(req)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -86,10 +94,16 @@ void updateProfileReturnsDto() throws Exception { @Test void getProfileRejectsCrossTenantScopedAdmin() throws Exception { String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of( + "accountId", + OTHER_ACCOUNT_UUID, + "scopedRoles", + Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( - get("/profiles/2") + get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isForbidden()); @@ -98,11 +112,17 @@ void getProfileRejectsCrossTenantScopedAdmin() throws Exception { @Test void getProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { String token = - jwtUtil.generateToken("3", Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of( + "accountId", + OTHER_ACCOUNT_UUID, + "scopedRoles", + Map.of("1", List.of("tenantAdmin")))); mockMvc .perform( - get("/profiles/2") + get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isForbidden()); @@ -112,11 +132,14 @@ void getProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { @Test void getProfileRejectsGlobalAdminForAnotherAccount() throws Exception { - String token = jwtUtil.generateToken("3", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( - get("/profiles/2") + get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isForbidden()); @@ -126,27 +149,33 @@ void getProfileRejectsGlobalAdminForAnotherAccount() throws Exception { @Test void getProfileRejectsMalformedAccountIdBeforeDispatch() throws Exception { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( - get("/profiles/not-a-number") + get("/profiles/not-a-uuid") .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("accountId must be numeric")); + .andExpect(jsonPath("$.error.message").value("accountId must be a canonical non-nil UUID")); verifyNoInteractions(accountService); } @Test void getProfileRejectsZeroTenantIdBeforeDispatch() throws Exception { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( - get("/profiles/2") + get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "0") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) @@ -159,15 +188,17 @@ void getProfileRejectsZeroTenantIdBeforeDispatch() throws Exception { @Test void updateProfileAllowsCurrentAccountWithoutPrivilegedTenantRole() throws Exception { UpdateProfileRequest req = - new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + new UpdateProfileRequest( + 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); ProfileDto dto = - new ProfileDto(1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + new ProfileDto( + 1L, 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); when(accountService.updateProfile(req)).thenReturn(dto); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(req)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -179,12 +210,12 @@ void updateProfileAllowsCurrentAccountWithoutPrivilegedTenantRole() throws Excep void updateProfileRejectsReservedHiddenStaffPolicyBeforeDispatch() throws Exception { UpdateProfileRequest request = new UpdateProfileRequest( - 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -201,12 +232,13 @@ void updateProfileRejectsReservedHiddenStaffPolicyBeforeDispatch() throws Except void updateProfileRejectsUnauthorizedCallerBeforeReservedPolicyValidation() throws Exception { UpdateProfileRequest request = new UpdateProfileRequest( - 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); - String token = jwtUtil.generateToken("3", Map.of("accountId", "3")); + 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); + String token = + jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("accountId", OTHER_ACCOUNT_UUID)); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -218,13 +250,20 @@ void updateProfileRejectsUnauthorizedCallerBeforeReservedPolicyValidation() thro @Test void updateProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { UpdateProfileRequest request = - new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + new UpdateProfileRequest( + 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); String token = - jwtUtil.generateToken("3", Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of( + "accountId", + OTHER_ACCOUNT_UUID, + "scopedRoles", + Map.of("1", List.of("tenantAdmin")))); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -236,12 +275,16 @@ void updateProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { @Test void updateProfileRejectsGlobalAdminForAnotherAccount() throws Exception { UpdateProfileRequest request = - new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); - String token = jwtUtil.generateToken("3", Map.of("globalRoles", List.of("platformAdmin"))); + new UpdateProfileRequest( + 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + String token = + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -253,8 +296,12 @@ void updateProfileRejectsGlobalAdminForAnotherAccount() throws Exception { @Test void updateProfileRejectsZeroAccountIdBeforeDispatch() throws Exception { UpdateProfileRequest req = - new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + new UpdateProfileRequest( + 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + String token = + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -264,7 +311,7 @@ void updateProfileRejectsZeroAccountIdBeforeDispatch() throws Exception { .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("accountId must be positive")); + .andExpect(jsonPath("$.error.message").value("accountId must be a canonical non-nil UUID")); verifyNoInteractions(accountService); } @@ -272,12 +319,13 @@ void updateProfileRejectsZeroAccountIdBeforeDispatch() throws Exception { @Test void updateProfileRejectsZeroTenantIdBeforeDispatch() throws Exception { UpdateProfileRequest req = - new UpdateProfileRequest(0L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + new UpdateProfileRequest( + 0L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(req)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -287,4 +335,45 @@ void updateProfileRejectsZeroTenantIdBeforeDispatch() throws Exception { verifyNoInteractions(accountService); } + + @Test + void updateProfileRejectsChangedBodyAccountBeforeDispatch() throws Exception { + UpdateProfileRequest request = + new UpdateProfileRequest( + 1L, OTHER_ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); + + mockMvc + .perform( + put("/profiles/" + ACCOUNT_UUID) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request)) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isBadRequest()); + + verifyNoInteractions(accountService); + } + + @Test + void getProfileRefusesWrongOwnerProjection() throws Exception { + when(accountService.resolveAccountStorageId(java.util.UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + when(accountService.getProfile(1L, 2L)) + .thenReturn( + new ProfileDto( + 1L, + 1L, + OTHER_ACCOUNT_UUID, + "private", + "secret", + ProfilePresenceVisibilityPolicy.PRIVATE)); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); + + mockMvc + .perform( + get("/profiles/" + ACCOUNT_UUID) + .param("tenantId", "1") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isServiceUnavailable()); + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java index f6dfd7e760..456a5c2141 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java @@ -40,7 +40,10 @@ void playerBootstrapRemainsPublicInProdProfile() throws Exception { when(accountService.issuePlayerBootstrap("demo@example.com", "swordfish")) .thenReturn( new PlayerBootstrapResult( - 1L, "boot123", "2026-03-30T00:00:00Z", "2026-03-30T00:05:00Z")); + "4cae05e8-7a6b-4b14-9d44-665e3eec450b", + "boot123", + "2026-03-30T00:00:00Z", + "2026-03-30T00:05:00Z")); mockMvc .perform( @@ -49,7 +52,7 @@ void playerBootstrapRemainsPublicInProdProfile() throws Exception { .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.accountId").value(1)) + .andExpect(jsonPath("$.data.accountId").value("4cae05e8-7a6b-4b14-9d44-665e3eec450b")) .andExpect(jsonPath("$.data.bootstrapToken").value("boot123")); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AuthenticationResultTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AuthenticationResultTest.java new file mode 100644 index 0000000000..755a553ad1 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AuthenticationResultTest.java @@ -0,0 +1,40 @@ +package net.firedevops.firemud.accountservice.dto; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; + +class AuthenticationResultTest { + @Test + void acceptsCanonicalNonNilAccountUuid() { + AuthenticationResult result = + new AuthenticationResult("4cae05e8-7a6b-4b14-9d44-665e3eec450b", "token"); + + assertEquals("4cae05e8-7a6b-4b14-9d44-665e3eec450b", result.accountId()); + } + + @ParameterizedTest + @NullSource + @ValueSource( + strings = { + "", + " ", + "12", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "4CAE05E8-7A6B-4B14-9D44-665E3EEC450B", + "1-1-1-1-1", + " 4cae05e8-7a6b-4b14-9d44-665e3eec450b" + }) + void rejectsNonCanonicalOrNilAccountUuid(String accountId) { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, () -> new AuthenticationResult(accountId, "token")); + + assertEquals("accountId must be a canonical non-nil UUID", exception.getMessage()); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountRuntimeConsumerAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountRuntimeConsumerAuthWiringTest.java new file mode 100644 index 0000000000..7807772628 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountRuntimeConsumerAuthWiringTest.java @@ -0,0 +1,406 @@ +package unit.net.firedevops.firemud.accountservice.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.protobuf.ProtoUtils; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; +import net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesRequest; +import net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse; +import net.firedevops.firemud.accountservice.dto.RealmAccessGrantResult; +import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.PingService; +import net.firedevops.firemud.accountservice.service.impl.AccountGrpcService; +import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import net.firedevops.firemud.common.security.JwtClaims; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionClaims; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.FileSystemResource; + +class AccountRuntimeConsumerAuthWiringTest { + private static final String IDENTITY_METHOD = + "account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity"; + private static final String NONPUBLIC_METHOD = "account.v1.AccountService/GetProfile"; + private static final String REALM_GRANT_METHOD = + "account.v1.AccountService/GetRealmAccessGrantForRuntime"; + private static final String PRESENCE_METHOD = + "account.v1.AccountService/ListPresenceVisibilityPolicies"; + private static final String ACCOUNT_UUID = "87426bb3-a733-43f0-9c8e-2e379cbdf7ec"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String SOCIAL_GROUPS_URI = + "spiffe://firemud/ns/test/sa/social-groups-service"; + private static final MethodDescriptor< + GetRealmAccessGrantForRuntimeRequest, GetRealmAccessGrantForRuntimeResponse> + REALM_GRANT_METHOD_DESCRIPTOR = + unaryMethod( + REALM_GRANT_METHOD, + GetRealmAccessGrantForRuntimeRequest.getDefaultInstance(), + GetRealmAccessGrantForRuntimeResponse.getDefaultInstance()); + private static final MethodDescriptor< + ListPresenceVisibilityPoliciesRequest, ListPresenceVisibilityPoliciesResponse> + PRESENCE_METHOD_DESCRIPTOR = + unaryMethod( + PRESENCE_METHOD, + ListPresenceVisibilityPoliciesRequest.getDefaultInstance(), + ListPresenceVisibilityPoliciesResponse.getDefaultInstance()); + + @Test + void realmGrantMethodAllowsOnlyExactSameNamespaceGameSessionWorkloadUnderBothYamlLayers() { + for (boolean productionLayer : List.of(false, true)) { + withConfiguredInterceptor( + productionLayer, + (interceptor, jwtUtil) -> { + AccountService accountService = mock(AccountService.class); + when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); + when(accountService.getRealmAccessGrantForRuntime(42L, 1L, "demo", "preview", "req-1")) + .thenReturn( + new RealmAccessGrantResult( + 42L, 1L, "demo", "preview", true, 2L, Instant.now().toString())); + AccountGrpcService service = + new AccountGrpcService(mock(PingService.class), accountService, null, "test"); + String bearer = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); + + GrantDispatchResult valid = + dispatchRealmGrantMethod(interceptor, service, GAME_SESSION_URI, null); + assertThat(valid.handlerDispatched()).isTrue(); + assertThat(valid.observer().completed).isTrue(); + assertThat(valid.observer().response.getAccountId()).isEqualTo(ACCOUNT_UUID); + verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + + AccountService deniedService = mock(AccountService.class); + AccountGrpcService deniedHandler = + new AccountGrpcService(mock(PingService.class), deniedService, null, "test"); + GrantDispatchResult bearerOnly = + dispatchRealmGrantMethod(interceptor, deniedHandler, null, bearer); + GrantDispatchResult wrongNamespace = + dispatchRealmGrantMethod( + interceptor, + deniedHandler, + "spiffe://firemud/ns/other/sa/game-session-service", + null); + for (GrantDispatchResult denied : List.of(bearerOnly, wrongNamespace)) { + assertThat(denied.observer().completed).isTrue(); + assertThat(denied.observer().response.getError().getCode()) + .isEqualTo("PERMISSION_DENIED"); + } + verifyNoInteractions(deniedService); + }); + } + } + + @Test + void exactSocialPeerReachesPresencePolicyHandlerWithoutBearerUnderBothYamlLayers() { + for (boolean productionLayer : List.of(false, true)) { + withConfiguredInterceptor( + productionLayer, + (interceptor, ignored) -> { + AccountService accountService = mock(AccountService.class); + when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); + when(accountService.listPresenceVisibilityPolicies(1L, List.of(42L))) + .thenReturn(Map.of(42L, ProfilePresenceVisibilityPolicy.PRIVATE)); + AccountGrpcService service = + new AccountGrpcService(mock(PingService.class), accountService, null, "test"); + + PresenceDispatchResult result = + dispatchPresenceMethod(interceptor, service, SOCIAL_GROUPS_URI, null); + + assertThat(result.handlerDispatched()).isTrue(); + assertThat(result.observer().completed).isTrue(); + assertThat(result.observer().response.getPoliciesCount()).isEqualTo(1); + assertThat(result.observer().response.getPolicies(0).getAccountId()) + .isEqualTo(ACCOUNT_UUID); + assertThat(result.observer().response.getPolicies(0).getPolicy()).isEqualTo("PRIVATE"); + verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + verify(accountService).listPresenceVisibilityPolicies(1L, List.of(42L)); + }); + } + } + + @Test + void bearerOnlyPresenceRequestReachesHandlerButIsDeniedWithoutSocialPeerUnderBothYamlLayers() { + for (boolean productionLayer : List.of(false, true)) { + withConfiguredInterceptor( + productionLayer, + (interceptor, jwtUtil) -> { + AccountService accountService = mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(mock(PingService.class), accountService, null, "test"); + String bearer = + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of( + "accountId", + ACCOUNT_UUID, + "globalRoles", + List.of("platformAdmin"), + "scopedRoles", + Map.of())); + + var validatedBearer = jwtUtil.parseToken(bearer); + assertThat( + JwtClaims.requireSignedGameplayAccountUuid( + validatedBearer.getPayload(), "Bearer subject/account UUID mismatch")) + .isEqualTo(ACCOUNT_UUID); + assertThat(SessionClaims.fromJwt(validatedBearer).hasPrivilegedRole()).isTrue(); + + PresenceDispatchResult result = + dispatchPresenceMethod(interceptor, service, null, bearer); + + assertThat(result.handlerDispatched()).isTrue(); + assertThat(result.observer().completed).isTrue(); + assertThat(result.observer().response.getError().getCode()) + .isEqualTo("PERMISSION_DENIED"); + verifyNoInteractions(accountService); + }); + } + } + + private static PresenceDispatchResult dispatchPresenceMethod( + AuthTokenInterceptor interceptor, + AccountGrpcService service, + String peerUri, + String bearerToken) { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = + mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(PRESENCE_METHOD_DESCRIPTOR); + AtomicBoolean handlerDispatched = new AtomicBoolean(); + PresenceTestObserver observer = new PresenceTestObserver(); + ServerCallHandler + next = + new ServerCallHandler<>() { + @Override + public ServerCall.Listener startCall( + ServerCall< + ListPresenceVisibilityPoliciesRequest, + ListPresenceVisibilityPoliciesResponse> + serverCall, + Metadata headers) { + handlerDispatched.set(true); + return new ServerCall.Listener<>() { + @Override + public void onMessage(ListPresenceVisibilityPoliciesRequest request) { + service.listPresenceVisibilityPolicies(request, observer); + } + }; + } + }; + ListPresenceVisibilityPoliciesRequest request = + ListPresenceVisibilityPoliciesRequest.newBuilder() + .setTenantId("1") + .addAccountIds(ACCOUNT_UUID) + .build(); + Metadata headers = new Metadata(); + if (bearerToken != null) { + headers.put( + Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER), + "Bearer " + bearerToken); + } + Runnable dispatch = + () -> { + ServerCall.Listener listener = + interceptor.interceptCall(call, headers, next); + listener.onMessage(request); + }; + + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(dispatch); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(dispatch); + } + return new PresenceDispatchResult(observer, handlerDispatched.get()); + } + + private static GrantDispatchResult dispatchRealmGrantMethod( + AuthTokenInterceptor interceptor, + AccountGrpcService service, + String peerUri, + String bearerToken) { + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = + mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(REALM_GRANT_METHOD_DESCRIPTOR); + AtomicBoolean handlerDispatched = new AtomicBoolean(); + GrantTestObserver observer = new GrantTestObserver(); + ServerCallHandler + next = + new ServerCallHandler<>() { + @Override + public ServerCall.Listener startCall( + ServerCall< + GetRealmAccessGrantForRuntimeRequest, + GetRealmAccessGrantForRuntimeResponse> + serverCall, + Metadata headers) { + handlerDispatched.set(true); + return new ServerCall.Listener<>() { + @Override + public void onMessage(GetRealmAccessGrantForRuntimeRequest request) { + service.getRealmAccessGrantForRuntime(request, observer); + } + }; + } + }; + GetRealmAccessGrantForRuntimeRequest request = + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("1") + .setWorldSlug("demo") + .setRealmSlug("preview") + .setRequestId("req-1") + .build(); + Metadata headers = new Metadata(); + if (bearerToken != null) { + headers.put( + Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER), + "Bearer " + bearerToken); + } + Runnable dispatch = + () -> { + ServerCall.Listener listener = + interceptor.interceptCall(call, headers, next); + listener.onMessage(request); + }; + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(dispatch); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(dispatch); + } + return new GrantDispatchResult(observer, handlerDispatched.get()); + } + + private static void withConfiguredInterceptor( + boolean productionLayer, + java.util.function.BiConsumer action) { + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonSecurityAutoConfiguration.class)) + .withInitializer( + context -> { + try { + YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader(); + PropertySource accountBase = + yamlLoader + .load( + "account-application", + new FileSystemResource("src/main/resources/application.yml")) + .get(0); + context.getEnvironment().getPropertySources().addLast(accountBase); + if (productionLayer) { + PropertySource accountProduction = + yamlLoader + .load( + "account-application-prod", + new FileSystemResource("src/main/resources/application-prod.yml")) + .get(0); + context.getEnvironment().getPropertySources().addFirst(accountProduction); + } + } catch (IOException exception) { + throw new IllegalStateException( + "Could not load Account application config", exception); + } + }) + .withPropertyValues("firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234") + .run( + context -> { + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .contains(IDENTITY_METHOD) + .contains(PRESENCE_METHOD) + .contains(REALM_GRANT_METHOD) + .doesNotContain(NONPUBLIC_METHOD); + action.accept( + context.getBean(AuthTokenInterceptor.class), context.getBean(JwtUtil.class)); + }); + } + + private static < + ReqT extends com.google.protobuf.Message, RespT extends com.google.protobuf.Message> + MethodDescriptor unaryMethod( + String fullMethodName, ReqT requestDefault, RespT responseDefault) { + return MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(fullMethodName) + .setRequestMarshaller(ProtoUtils.marshaller(requestDefault)) + .setResponseMarshaller(ProtoUtils.marshaller(responseDefault)) + .build(); + } + + private record PresenceDispatchResult(PresenceTestObserver observer, boolean handlerDispatched) {} + + private record GrantDispatchResult(GrantTestObserver observer, boolean handlerDispatched) {} + + private static final class GrantTestObserver + implements StreamObserver { + private GetRealmAccessGrantForRuntimeResponse response; + private boolean completed; + + @Override + public void onNext(GetRealmAccessGrantForRuntimeResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + throw new AssertionError("Expected Account application response", throwable); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private static final class PresenceTestObserver + implements StreamObserver { + private ListPresenceVisibilityPoliciesResponse response; + private boolean completed; + + @Override + public void onNext(ListPresenceVisibilityPoliciesResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + throw new AssertionError("Expected Account application response", throwable); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index c4b55c6db0..28985b7222 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -8,6 +8,8 @@ import io.grpc.Context; import io.grpc.Status; import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.UUID; @@ -51,6 +53,7 @@ import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; +import net.firedevops.firemud.accountservice.dto.RealmAccessGrantResult; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.PingService; @@ -64,9 +67,12 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; +import org.springframework.dao.DataAccessResourceFailureException; class AccountGrpcServiceTest { private static final String WORKLOAD_NAMESPACE = "test"; + private static final String ACCOUNT_UUID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + private static final String OTHER_ACCOUNT_UUID = "a2e1342e-a139-49c6-a460-c8e25f6697ae"; private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; private static final String OTHER_REALM_ID = "57c58f36-c5ea-4aa8-8ef7-91a45e407f01"; private static final String PLAYABLE_STATE_NAMESPACE_ID = "c6ed6a44-c7e7-4f18-81fc-078a74e67c07"; @@ -75,10 +81,20 @@ class AccountGrpcServiceTest { "spiffe://firemud/ns/test/sa/game-session-service", WORKLOAD_NAMESPACE, "game-session-service"); + private static final GrpcPeerIdentity SOCIAL_GROUPS_PEER = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/social-groups-service", + WORKLOAD_NAMESPACE, + "social-groups-service"); + private static final GrpcPeerIdentity WORLD_MANAGEMENT_PEER = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/world-management-service", + WORKLOAD_NAMESPACE, + "world-management-service"); private static PlayerExecutionContext validPlayerContext() { return PlayerExecutionContext.newBuilder() - .setAccountId("10") + .setAccountId(ACCOUNT_UUID) .setTenantId("20") .setRealmId(REALM_ID) .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) @@ -160,6 +176,8 @@ public void onCompleted() {} void issueDirectTextConnectScopeAcceptsExactGameSessionPeerAndTypedTarget() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(10L); Mockito.when( accountService.issueDirectTextConnectScope( Mockito.any(DirectTextCallerContext.class), @@ -174,6 +192,7 @@ void issueDirectTextConnectScopeAcceptsExactGameSessionPeerAndTypedTarget() { () -> service.issueDirectTextConnectScope(validScopeRequest(), observer)); assertTrue(observer.completed()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); assertEquals("scope-1", observer.response().getConnectScopeId()); assertEquals("2026-09-24T12:00:00Z", observer.response().getConnectScopeExpiresAt()); Mockito.verify(accountService) @@ -268,6 +287,8 @@ void verifyEmailMapsMissingSourceToSafeUnavailableAndPreservesOtherExceptions() void joinPublicProductionMembershipPreservesStoredFailureOutcome() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(10L); Mockito.when( accountService.joinPublicProductionFromGameSession( Mockito.any(DirectTextCallerContext.class), @@ -286,7 +307,7 @@ void joinPublicProductionMembershipPreservesStoredFailureOutcome() { assertTrue(observer.completed()); assertFalse(observer.response().getSuccess()); assertEquals("ENTITLEMENT_UNAVAILABLE", observer.response().getOutcomeCode()); - assertEquals("10", observer.response().getAccountId()); + assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); assertEquals("20", observer.response().getTenantId()); assertEquals("0", observer.response().getMembershipId()); assertTrue(observer.response().getReplayed()); @@ -309,6 +330,8 @@ void joinPublicProductionMembershipPreservesStoredFailureOutcome() { void issueDirectTextConnectScopeMapsUnexpectedFailureToRetryableUnavailable() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(10L); Mockito.when( accountService.issueDirectTextConnectScope( Mockito.any(DirectTextCallerContext.class), @@ -333,6 +356,8 @@ void issueDirectTextConnectScopeMapsUnexpectedFailureToRetryableUnavailable() { void joinPublicProductionMembershipMapsUnexpectedFailureToRetryableUnavailable() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(10L); Mockito.when( accountService.joinPublicProductionFromGameSession( Mockito.any(DirectTextCallerContext.class), @@ -540,6 +565,68 @@ void directTextMethodsRejectNoncanonicalPlayableStateNamespaceIdsAtIngress(Strin Mockito.verifyNoInteractions(accountService); } + @ParameterizedTest + @ValueSource( + strings = { + "10", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "4CAE05E8-7A6B-4B14-9D44-665E3EEC450B" + }) + void directTextMethodsRejectNoncanonicalAccountBeforeOwnerLookup(String accountId) { + AccountService owner = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), owner, null, WORKLOAD_NAMESPACE); + PlayerExecutionContext context = + validPlayerContext().toBuilder().setAccountId(accountId).build(); + RecordingObserver scope = new RecordingObserver<>(); + RecordingObserver join = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.issueDirectTextConnectScope( + validScopeRequest().toBuilder().setPlayerContext(context).build(), scope)); + withPeer( + GAME_SESSION_PEER, + () -> + service.joinPublicProductionMembership( + validJoinRequest().toBuilder().setPlayerContext(context).build(), join)); + + assertEquals("INVALID_ARGUMENT", scope.response().getError().getCode()); + assertEquals("INVALID_ARGUMENT", join.response().getError().getCode()); + Mockito.verifyNoInteractions(owner); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void joinRejectsPrivateResultThatDoesNotMatchValidatedCaller(boolean changedAccount) { + AccountService owner = Mockito.mock(AccountService.class); + Mockito.when(owner.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))).thenReturn(10L); + Mockito.when(owner.joinPublicProductionFromGameSession(Mockito.any(), Mockito.any())) + .thenReturn( + new JoinPublicProductionResult( + false, + "ENTITLEMENT_UNAVAILABLE", + changedAccount ? 11L : 10L, + changedAccount ? 20L : 21L, + 0L, + 0L, + 0L, + true)); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), owner, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> service.joinPublicProductionMembership(validJoinRequest(), observer)); + + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals("", observer.response().getAccountId()); + assertFalse(observer.response().getSuccess()); + } + @Test void authenticateFailureReturnsErrorDetail() { PingService pingService = Mockito.mock(PingService.class); @@ -573,6 +660,32 @@ public void onCompleted() {} Mockito.verify(accountService).authenticateForGameplay("demo@example.com", "bad"); } + @Test + void authenticateConvertsIllegalStateToBoundedAuthorityUnavailableError() { + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.authenticateForGameplay("demo@example.com", "password")) + .thenThrow(new IllegalStateException("private provenance detail")); + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), accountService, registry); + RecordingObserver observer = new RecordingObserver<>(); + + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + observer); + + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals( + "Account authority unavailable; retry later", observer.response().getError().getMessage()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + assertEquals( + 1.0, registry.get("grpc.app_error").tag("code", "AUTH_UNAVAILABLE").counter().count()); + } + @Test void requestEmailLoginOtpDispatchesNeutralChallengeRequest() { PingService pingService = Mockito.mock(PingService.class); @@ -624,7 +737,9 @@ void verifyEmailLoginOtpReturnsAuthenticatedSession() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.verifyEmailLoginOtp("demo@example.com", "123456")) - .thenReturn(new net.firedevops.firemud.accountservice.dto.AuthenticationResult(9L, "jwt")); + .thenReturn( + new net.firedevops.firemud.accountservice.dto.AuthenticationResult( + ACCOUNT_UUID, "jwt")); AccountGrpcService service = new AccountGrpcService(pingService, accountService); AtomicReference ref = new AtomicReference<>(); @@ -647,10 +762,33 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("9", ref.get().getAccountId()); + assertEquals(ACCOUNT_UUID, ref.get().getAccountId()); assertEquals("jwt", ref.get().getAuthToken()); } + @Test + void authenticateReturnsCanonicalUuid() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.authenticateForGameplay("demo@example.com", "password")) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.AuthenticationResult( + ACCOUNT_UUID, "jwt")); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + RecordingObserver observer = new RecordingObserver<>(); + + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + observer); + + assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); + assertEquals("jwt", observer.response().getAuthToken()); + assertTrue(observer.completed()); + } + @Test void verifyEmailLoginOtpReturnsInvalidCredentialsAsApplicationError() { PingService pingService = Mockito.mock(PingService.class); @@ -676,6 +814,32 @@ void verifyEmailLoginOtpReturnsInvalidCredentialsAsApplicationError() { assertFalse(observer.receivedTransportError()); } + @Test + void verifyEmailLoginOtpConvertsIllegalStateToBoundedAuthorityUnavailableError() { + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.verifyEmailLoginOtp("demo@example.com", "123456")) + .thenThrow(new IllegalStateException("private provenance detail")); + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), accountService, registry); + RecordingObserver observer = new RecordingObserver<>(); + + service.verifyEmailLoginOtp( + VerifyEmailLoginOtpRequest.newBuilder() + .setEmail("demo@example.com") + .setCode("123456") + .build(), + observer); + + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals( + "Account authority unavailable; retry later", observer.response().getError().getMessage()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + assertEquals( + 1.0, registry.get("grpc.app_error").tag("code", "AUTH_UNAVAILABLE").counter().count()); + } + @Test void createAccountValidationErrorReturnsErrorDetail() { PingService pingService = Mockito.mock(PingService.class); @@ -821,31 +985,91 @@ public void onCompleted() {} assertEquals("e@example.com", captor.getValue().email()); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void profileProjectionBindsCanonicalCallerAndRejectsChangedOwner(boolean changedOwner) { + AccountService owner = Mockito.mock(AccountService.class); + Mockito.when(owner.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))).thenReturn(2L); + var dto = + new net.firedevops.firemud.accountservice.dto.ProfileDto( + 1L, + 1L, + changedOwner ? OTHER_ACCOUNT_UUID : ACCOUNT_UUID, + "demo", + "bio", + ProfilePresenceVisibilityPolicy.PRIVATE); + Mockito.when(owner.getProfile(1L, 2L)).thenReturn(dto); + Mockito.when(owner.updateProfile(Mockito.any())).thenReturn(dto); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), owner, null, WORKLOAD_NAMESPACE); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + RecordingObserver get = new RecordingObserver<>(); + RecordingObserver update = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> { + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), + get); + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .setProfileJson( + "{\"displayName\":\"demo\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + update); + }); + + var command = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.accountservice.dto.UpdateProfileRequest.class); + Mockito.verify(owner).updateProfile(command.capture()); + assertEquals(ACCOUNT_UUID, command.getValue().accountId()); + if (changedOwner) { + assertEquals("AUTH_UNAVAILABLE", get.response().getError().getCode()); + assertEquals("", get.response().getProfileJson()); + assertEquals("AUTH_UNAVAILABLE", update.response().getError().getCode()); + assertFalse(update.response().getSuccess()); + } else { + assertTrue(get.response().getProfileJson().contains(ACCOUNT_UUID)); + assertTrue(update.response().getSuccess()); + } + } + @Test void getProfileReturnsProfile() throws Exception { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); Mockito.when(accountService.getProfile(1L, 2L)) .thenReturn( new net.firedevops.firemud.accountservice.dto.ProfileDto( - 1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE)); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + 1L, 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE)); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("2").build(), - new StreamObserver() { - @Override - public void onNext(GetProfileResponse value) { - ref.set(value); - } + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), + new StreamObserver() { + @Override + public void onNext(GetProfileResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertEquals( "demo", @@ -861,127 +1085,520 @@ public void onCompleted() {} .readTree(ref.get().getProfileJson()) .path("presenceVisibilityPolicy") .asText()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); } @Test void getProfileRejectsZeroAccountIdBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("0").build(), - new StreamObserver() { - @Override - public void onNext(GetProfileResponse value) { - ref.set(value); - } + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId("0").build(), + new StreamObserver() { + @Override + public void onNext(GetProfileResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertEquals("accountId must be a canonical non-nil UUID", ref.get().getError().getMessage()); + Mockito.verifyNoInteractions(accountService); + } + + @Test + void getProfileRejectsMismatchedCallerSubjectBeforeStorageResolution() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext(OTHER_ACCOUNT_UUID, List.of("player"), Map.of()); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + Mockito.verify(accountService, Mockito.never()) + .resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService, Mockito.never()).getProfile(1L, 2L); + } + + @ParameterizedTest + @ValueSource(strings = {"resolution", "profile"}) + void getProfileBoundsUnprovedIdentityAndUnavailableAuthority(String failureStage) { + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + if ("resolution".equals(failureStage)) { + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenThrow(new IllegalStateException("private Account source-row provenance detail")); + } else { + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.getProfile(1L, 2L)) + .thenThrow(new DataAccessResourceFailureException("private Account database detail")); + } + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), + observer)); + + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals( + "Account authority unavailable; retry later", observer.response().getError().getMessage()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + } + + @ParameterizedTest + @ValueSource(strings = {"resolution", "profile"}) + void updateProfileBoundsUnprovedIdentityAndUnavailableAuthority(String failureStage) { + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + if ("resolution".equals(failureStage)) { + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenThrow(new IllegalStateException("private Account source-row provenance detail")); + } else { + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.updateProfile(Mockito.any())) + .thenThrow(new DataAccessResourceFailureException("private Account database detail")); + } + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .setProfileJson( + "{\"displayName\":\"demo\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + observer)); + + assertFalse(observer.response().getSuccess()); + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals( + "Account authority unavailable; retry later", observer.response().getError().getMessage()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + } + + @Test + void profileMethodsPreserveMissingAccountOutcome() { + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenThrow(new IllegalArgumentException("Account not found")); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + RecordingObserver getObserver = new RecordingObserver<>(); + RecordingObserver updateObserver = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> { + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), + getObserver); + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .setProfileJson("{}") + .build(), + updateObserver); + }); + + assertEquals("NOT_FOUND", getObserver.response().getError().getCode()); + assertEquals("NOT_FOUND", updateObserver.response().getError().getCode()); + assertTrue(getObserver.completed()); + assertTrue(updateObserver.completed()); + Mockito.verify(accountService, Mockito.never()).getProfile(1L, 2L); + Mockito.verify(accountService, Mockito.never()).updateProfile(Mockito.any()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + "42", + "1-1-1-1-1", + "00000000-0000-0000-0000-000000000000", + "4CAE05E8-7A6B-4B14-9D44-665E3EEC450B" + }) + void profileMethodsRejectNoncanonicalAccountUuidBeforeResolution(String accountUuid) { + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + RecordingObserver getObserver = new RecordingObserver<>(); + RecordingObserver updateObserver = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> { + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(accountUuid).build(), + getObserver); + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(accountUuid) + .setProfileJson("{}") + .build(), + updateObserver); + }); + + assertEquals("INVALID_ARGUMENT", getObserver.response().getError().getCode()); + assertEquals("INVALID_ARGUMENT", updateObserver.response().getError().getCode()); + assertTrue(getObserver.completed()); + assertTrue(updateObserver.completed()); + Mockito.verifyNoInteractions(accountService); + } + + @ParameterizedTest + @ValueSource(strings = {"", "{", "null", "[]", "{\"presenceVisibilityPolicy\":\"UNKNOWN\"}"}) + void updateProfileRejectsMalformedJsonAndPolicyWithInvalidArgument(String profileJson) { + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .setProfileJson(profileJson) + .build(), + observer)); + + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + Mockito.verify(accountService, Mockito.never()).updateProfile(Mockito.any()); + } + + @Test + void updateProfilePreservesCallerSubjectPermissionDenial() { + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + SessionContext.setContext(OTHER_ACCOUNT_UUID, List.of("player"), Map.of()); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .setProfileJson("{}") + .build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.completed()); Mockito.verifyNoInteractions(accountService); } + private static ListPresenceVisibilityPoliciesRequest presencePolicyRequest( + String... accountUuids) { + ListPresenceVisibilityPoliciesRequest.Builder builder = + ListPresenceVisibilityPoliciesRequest.newBuilder().setTenantId("1"); + for (String accountUuid : accountUuids) { + builder.addAccountIds(accountUuid); + } + return builder.build(); + } + @Test - void listPresenceVisibilityPoliciesMapsPersistedPolicies() { + void listPresenceVisibilityPoliciesResolvesAndReturnsCanonicalUuidKeysForSocialPeer() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(OTHER_ACCOUNT_UUID))) + .thenReturn(3L); Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L, 3L))) .thenReturn( Map.of( 2L, ProfilePresenceVisibilityPolicy.PRIVATE, 3L, ProfilePresenceVisibilityPolicy.HIDDEN_STAFF)); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("2") - .addAccountIds("3") - .addAccountIds("2") - .build(), - observer); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + presencePolicyRequest(ACCOUNT_UUID, OTHER_ACCOUNT_UUID, ACCOUNT_UUID), observer)); assertNotNull(observer.response()); assertEquals(2, observer.response().getPoliciesCount()); + assertEquals( + java.util.Set.of(ACCOUNT_UUID, OTHER_ACCOUNT_UUID), + observer.response().getPoliciesList().stream() + .map(entry -> entry.getAccountId()) + .collect(java.util.stream.Collectors.toSet())); assertTrue( observer.response().getPoliciesList().stream() .anyMatch( - entry -> entry.getAccountId().equals("2") && entry.getPolicy().equals("PRIVATE"))); + entry -> + entry.getAccountId().equals(ACCOUNT_UUID) + && entry.getPolicy().equals("PRIVATE"))); assertTrue( observer.response().getPoliciesList().stream() .anyMatch( entry -> - entry.getAccountId().equals("3") && entry.getPolicy().equals("HIDDEN_STAFF"))); + entry.getAccountId().equals(OTHER_ACCOUNT_UUID) + && entry.getPolicy().equals("HIDDEN_STAFF"))); assertTrue(observer.completed()); assertFalse(observer.receivedTransportError()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(OTHER_ACCOUNT_UUID)); Mockito.verify(accountService).listPresenceVisibilityPolicies(1L, List.of(2L, 3L)); } - @Test - void listPresenceVisibilityPoliciesRejectsNonPositiveAccountId() { + @ParameterizedTest + @ValueSource( + strings = { + "2", + "0", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "4CAE05E8-7A6B-4B14-9D44-665E3EEC450B" + }) + void listPresenceVisibilityPoliciesRejectsNonCanonicalAccountUuidBeforeResolution( + String accountId) { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("0") - .build(), - observer); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + presencePolicyRequest(ACCOUNT_UUID, accountId), observer)); - assertNotNull(observer.response()); assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); - assertEquals("accountId must be positive", observer.response().getError().getMessage()); assertTrue(observer.completed()); assertFalse(observer.receivedTransportError()); Mockito.verifyNoInteractions(accountService); } @Test - void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors() { + void listPresenceVisibilityPoliciesRejectsOverLimitBeforeResolution() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + String[] accountUuids = + java.util.stream.LongStream.rangeClosed(1L, 101L) + .mapToObj(value -> new UUID(0L, value).toString()) + .toArray(String[]::new); - Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) - .thenThrow(new IllegalArgumentException("Tenant not found")); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies(presencePolicyRequest(accountUuids), observer)); + + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verifyNoInteractions(accountService); + } + + @Test + void listPresenceVisibilityPoliciesRequiresExactSocialWorkloadPeer() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + List deniedPeers = + List.of( + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/account-service", "test", "account-service"), + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/social-groups-service", + "other", + "social-groups-service"), + GAME_SESSION_PEER); + RecordingObserver noPeerObserver = + new RecordingObserver<>(); + + service.listPresenceVisibilityPolicies(presencePolicyRequest(ACCOUNT_UUID), noPeerObserver); + for (GrpcPeerIdentity peer : deniedPeers) { + RecordingObserver observer = + new RecordingObserver<>(); + withPeer( + peer, + () -> + service.listPresenceVisibilityPolicies( + presencePolicyRequest(ACCOUNT_UUID), observer)); + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.completed()); + } + + assertEquals("PERMISSION_DENIED", noPeerObserver.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + + @Test + void listPresenceVisibilityPoliciesOmitsUnknownAndUnprovenSubjects() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + String unprovenAccountUuid = "00000000-0000-4000-8000-000000000003"; + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(OTHER_ACCOUNT_UUID))) + .thenThrow(new IllegalArgumentException("Account not found")); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(unprovenAccountUuid))) + .thenThrow(new IllegalStateException("Account identity provenance is unavailable")); + Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) + .thenReturn(Map.of(2L, ProfilePresenceVisibilityPolicy.FRIENDS_ONLY)); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + presencePolicyRequest(ACCOUNT_UUID, OTHER_ACCOUNT_UUID, unprovenAccountUuid), + observer)); + + assertEquals(1, observer.response().getPoliciesCount()); + assertEquals(ACCOUNT_UUID, observer.response().getPolicies(0).getAccountId()); + assertEquals("FRIENDS_ONLY", observer.response().getPolicies(0).getPolicy()); + Mockito.verify(accountService).listPresenceVisibilityPolicies(1L, List.of(2L)); + } + + @Test + void listPresenceVisibilityPoliciesRejectsAliasedResolverRowsWithoutPolicyRead() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(OTHER_ACCOUNT_UUID))) + .thenReturn(2L); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + presencePolicyRequest(ACCOUNT_UUID, OTHER_ACCOUNT_UUID), observer)); + + assertEquals("INTERNAL", observer.response().getError().getCode()); + assertEquals(0, observer.response().getPoliciesCount()); + Mockito.verify(accountService, Mockito.never()) + .listPresenceVisibilityPolicies(Mockito.anyLong(), Mockito.anyList()); + } + + @Test + void listPresenceVisibilityPoliciesRejectsUnexpectedStorageRowsWithoutPolicyResults() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) + .thenReturn(Map.of(3L, ProfilePresenceVisibilityPolicy.PRIVATE)); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies(presencePolicyRequest(ACCOUNT_UUID), observer)); + + assertEquals("INTERNAL", observer.response().getError().getCode()); + assertEquals(0, observer.response().getPoliciesCount()); + } + + @Test + void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) + .thenThrow(new IllegalArgumentException("Tenant not found")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver notFoundObserver = new RecordingObserver<>(); - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("2") - .build(), - notFoundObserver); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + presencePolicyRequest(ACCOUNT_UUID), notFoundObserver)); assertEquals("NOT_FOUND", notFoundObserver.response().getError().getCode()); assertTrue(notFoundObserver.completed()); assertFalse(notFoundObserver.receivedTransportError()); Mockito.reset(accountService); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) .thenThrow(new IllegalStateException("Policy lookup unavailable")); RecordingObserver internalObserver = new RecordingObserver<>(); - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("2") - .build(), - internalObserver); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + presencePolicyRequest(ACCOUNT_UUID), internalObserver)); assertEquals("INTERNAL", internalObserver.response().getError().getCode()); assertTrue(internalObserver.completed()); @@ -992,59 +1609,74 @@ void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors void getTenantMembershipForRuntimeReturnsResponse() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) .thenReturn( new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( 2L, 1L, true, true, 44L, "ACTIVE", 9L, "2026-03-30T00:00:00Z")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.getTenantMembershipForRuntime( - GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") - .setTenantId("1") - .setRequestId("req-1") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantMembershipForRuntimeResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("1") + .setRequestId("req-1") + .build(), + new StreamObserver() { + @Override + public void onNext(GetTenantMembershipForRuntimeResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); - assertEquals("2", ref.get().getAccountId()); + assertEquals(ACCOUNT_UUID, ref.get().getAccountId()); assertTrue(ref.get().getMembershipExists()); assertTrue(ref.get().getGameplayAdmissionAllowed()); assertEquals(44L, ref.get().getMembershipVersion()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService).getTenantMembershipForRuntime(2L, 1L, "req-1"); } @Test void getTenantMembershipForRuntimePreservesMissingMembershipAndAdmissionAllowed() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) .thenReturn( new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( 2L, 1L, false, true, 44L, "MISSING", 0L, "2026-03-30T00:00:00Z")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.getTenantMembershipForRuntime( - GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") - .setTenantId("1") - .setRequestId("req-1") - .build(), - observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("1") + .setRequestId("req-1") + .build(), + observer)); assertNotNull(observer.response()); + assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); assertFalse(observer.response().getMembershipExists()); assertTrue(observer.response().getGameplayAdmissionAllowed()); assertTrue(observer.completed()); @@ -1055,27 +1687,31 @@ void getTenantMembershipForRuntimePreservesMissingMembershipAndAdmissionAllowed( void getTenantMembershipForRuntimeRejectsZeroTenantIdBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.getTenantMembershipForRuntime( - GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") - .setTenantId("0") - .setRequestId("req-1") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantMembershipForRuntimeResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("0") + .setRequestId("req-1") + .build(), + new StreamObserver() { + @Override + public void onNext(GetTenantMembershipForRuntimeResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); @@ -1083,40 +1719,234 @@ public void onCompleted() {} Mockito.verifyNoInteractions(accountService); } + @ParameterizedTest + @ValueSource( + strings = { + "2", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "4CAe05e8-7a6b-4b14-9d44-665e3eec450b" + }) + void getTenantMembershipForRuntimeRejectsNonCanonicalAccountId(String accountId) { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(accountId) + .setTenantId("1") + .setRequestId("req-1") + .build(), + observer)); + + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verifyNoInteractions(accountService); + } + @Test - void getRealmAccessGrantForRuntimeRejectsZeroAccountIdBeforeLookup() { + void getTenantMembershipForRuntimeRejectsMissingGameSessionPeer() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); - AtomicReference ref = new AtomicReference<>(); - service.getRealmAccessGrantForRuntime( - GetRealmAccessGrantForRuntimeRequest.newBuilder() - .setAccountId("0") + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) .setTenantId("1") - .setWorldSlug("demo") - .setRealmSlug("production") .setRequestId("req-1") .build(), - new StreamObserver() { - @Override - public void onNext(GetRealmAccessGrantForRuntimeResponse value) { - ref.set(value); - } + observer); - @Override - public void onError(Throwable t) {} + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verifyNoInteractions(accountService); + } - @Override - public void onCompleted() {} - }); + @Test + void getTenantMembershipForRuntimeFailsClosedWhenPrivateAccountDoesNotCorrelate() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( + 3L, 1L, true, true, 44L, "ACTIVE", 9L, "2026-03-30T00:00:00Z")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("1") + .setRequestId("req-1") + .build(), + observer)); + + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertTrue(observer.completed()); + } + + @Test + void getTenantMembershipForRuntimeFailsClosedWhenPrivateTenantDoesNotCorrelate() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( + 2L, 3L, true, true, 44L, "ACTIVE", 9L, "2026-03-30T00:00:00Z")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("1") + .setRequestId("req-1") + .build(), + observer)); + + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertTrue(observer.completed()); + } + + @Test + void getRealmAccessGrantForRuntimeRejectsNumericAccountIdBeforeLookup() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.getRealmAccessGrantForRuntime( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId("42") + .setTenantId("1") + .setWorldSlug("demo") + .setRealmSlug("production") + .setRequestId("req-1") + .build(), + observer)); + + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + assertEquals( + "accountId must be a canonical non-nil UUID", observer.response().getError().getMessage()); Mockito.verifyNoInteractions(accountService); } + @Test + void getRealmAccessGrantForRuntimeRequiresExactGameSessionPeer() { + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getRealmAccessGrantForRuntime( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("1") + .setWorldSlug("demo") + .setRealmSlug("production") + .setRequestId("req-1") + .build(), + observer)); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + Mockito.verifyNoInteractions(accountService); + } + + @Test + void getRealmAccessGrantForRuntimeResolvesUuidAndEchoesItAfterCorrelatedRead() { + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); + Mockito.when(accountService.getRealmAccessGrantForRuntime(42L, 7L, "demo", "preview", "req-1")) + .thenReturn( + new RealmAccessGrantResult( + 42L, 7L, "demo", "preview", true, 3L, Instant.now().toString())); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.getRealmAccessGrantForRuntime( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("preview") + .setRequestId("req-1") + .build(), + observer)); + + assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); + assertEquals("7", observer.response().getTenantId()); + assertEquals("demo", observer.response().getWorldSlug()); + assertEquals("preview", observer.response().getRealmSlug()); + assertEquals(3L, observer.response().getGrantVersion()); + assertTrue(observer.response().getGranted()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + } + + @Test + void getRealmAccessGrantForRuntimeFailsUnavailableOnMismatchedPrivateOwnerEvidence() { + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); + Mockito.when(accountService.getRealmAccessGrantForRuntime(42L, 7L, "demo", "preview", "req-1")) + .thenReturn( + new RealmAccessGrantResult( + 43L, 7L, "demo", "preview", true, 3L, Instant.now().toString())); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.getRealmAccessGrantForRuntime( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("preview") + .setRequestId("req-1") + .build(), + observer)); + + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + } + @Test void getTenantEntitlementsForRuntimeReturnsResponse() { PingService pingService = Mockito.mock(PingService.class); @@ -1125,32 +1955,126 @@ void getTenantEntitlementsForRuntimeReturnsResponse() { .thenReturn( new net.firedevops.firemud.accountservice.dto.RuntimeEntitlementsDto( 1L, true, true, 19L, 311L, "2026-03-30T00:00:00Z")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - AtomicReference ref = new AtomicReference<>(); - service.getTenantEntitlementsForRuntime( - GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") - .setRequestId("req-2") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantEntitlementsForRuntimeResponse value) { - ref.set(value); - } + RecordingObserver observer = new RecordingObserver<>(); + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("req-2") + .build(), + observer)); - @Override - public void onError(Throwable t) {} + assertNotNull(observer.response()); + assertEquals("1", observer.response().getTenantId()); + assertTrue(observer.response().getGameplayAvailable()); + assertTrue(observer.response().getAllowPublicJoin()); + assertEquals(19L, observer.response().getEntitlementVersion()); + assertTrue(observer.completed()); + Mockito.verify(accountService).getTenantEntitlementsForRuntime(1L, "req-2"); + } - @Override - public void onCompleted() {} - }); + @Test + void getTenantEntitlementsForRuntimeAllowsWorldManagementPeer() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.getTenantEntitlementsForRuntime(1L, "req-world")) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.RuntimeEntitlementsDto( + 1L, true, true, 19L, 311L, "2026-03-30T00:00:00Z")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); - assertNotNull(ref.get()); - assertEquals("1", ref.get().getTenantId()); - assertTrue(ref.get().getGameplayAvailable()); - assertTrue(ref.get().getAllowPublicJoin()); - assertEquals(19L, ref.get().getEntitlementVersion()); + withPeer( + WORLD_MANAGEMENT_PEER, + () -> + service.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("req-world") + .build(), + observer)); + + assertEquals("1", observer.response().getTenantId()); + assertTrue(observer.completed()); + Mockito.verify(accountService).getTenantEntitlementsForRuntime(1L, "req-world"); + } + + @Test + void getTenantEntitlementsForRuntimeRejectsAbsentWrongAndCrossNamespacePeers() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + List rejectedPeers = + java.util.Arrays.asList( + null, + SOCIAL_GROUPS_PEER, + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", + "other", + "game-session-service"), + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/world-management-service", + "other", + "world-management-service")); + + RecordingObserver absentPeerObserver = + new RecordingObserver<>(); + service.getTenantEntitlementsForRuntime(validEntitlementRequest(), absentPeerObserver); + assertEquals("PERMISSION_DENIED", absentPeerObserver.response().getError().getCode()); + for (GrpcPeerIdentity peer : rejectedPeers) { + RecordingObserver observer = + new RecordingObserver<>(); + withPeer( + peer, () -> service.getTenantEntitlementsForRuntime(validEntitlementRequest(), observer)); + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.completed()); + } + Mockito.verifyNoInteractions(accountService); + } + + @Test + void getTenantEntitlementsForRuntimeRejectsMalformedTenantOrRequestBeforeLookup() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + List malformedRequests = + List.of( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("0") + .setRequestId("req-1") + .build(), + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId(" ") + .build(), + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("x".repeat(129)) + .build()); + + for (GetTenantEntitlementsForRuntimeRequest request : malformedRequests) { + RecordingObserver observer = + new RecordingObserver<>(); + withPeer(GAME_SESSION_PEER, () -> service.getTenantEntitlementsForRuntime(request, observer)); + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + assertTrue(observer.completed()); + } + Mockito.verifyNoInteractions(accountService); + } + + private static GetTenantEntitlementsForRuntimeRequest validEntitlementRequest() { + return GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("req-2") + .build(); } @Test @@ -1162,26 +2086,30 @@ void getTenantEntitlementsForRuntimeReturnsUnavailableAuthorityError() { new AuthenticationException( "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous; retry later")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.getTenantEntitlementsForRuntime( - GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") - .setRequestId("req-ambiguous") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantEntitlementsForRuntimeResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("req-ambiguous") + .build(), + new StreamObserver() { + @Override + public void onNext(GetTenantEntitlementsForRuntimeResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertTrue(ref.get().hasError()); @@ -1192,26 +2120,30 @@ public void onCompleted() {} void getTenantEntitlementsForRuntimeRejectsZeroTenantIdBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.getTenantEntitlementsForRuntime( - GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("0") - .setRequestId("req-2") - .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantEntitlementsForRuntimeResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("0") + .setRequestId("req-2") + .build(), + new StreamObserver() { + @Override + public void onNext(GetTenantEntitlementsForRuntimeResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); @@ -1225,28 +2157,35 @@ void updateProfileErrorReturnsDetail() { AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.updateProfile(Mockito.any())) .thenThrow(new IllegalArgumentException("bad")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.updateProfile( - UpdateProfileRequest.newBuilder() - .setTenantId("1") - .setAccountId("2") - .setProfileJson( - "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") - .build(), - new StreamObserver() { - @Override - public void onNext(UpdateProfileResponse value) { - ref.set(value); - } + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + new StreamObserver() { + @Override + public void onNext(UpdateProfileResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); @@ -1256,28 +2195,32 @@ public void onCompleted() {} void updateProfileRejectsZeroTenantIdBeforeUpdate() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.updateProfile( - UpdateProfileRequest.newBuilder() - .setTenantId("0") - .setAccountId("2") - .setProfileJson( - "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") - .build(), - new StreamObserver() { - @Override - public void onNext(UpdateProfileResponse value) { - ref.set(value); - } + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("0") + .setAccountId(ACCOUNT_UUID) + .setProfileJson( + "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build(), + new StreamObserver() { + @Override + public void onNext(UpdateProfileResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); @@ -1291,11 +2234,13 @@ void exportAccountErrorReturnsDetail() { AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.exportAccountData(2L)) .thenThrow(new IllegalArgumentException("missing")); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); AccountGrpcService service = new AccountGrpcService(pingService, accountService); AtomicReference ref = new AtomicReference<>(); service.exportAccount( - ExportAccountRequest.newBuilder().setAccountId("2").build(), + ExportAccountRequest.newBuilder().setAccountId(ACCOUNT_UUID).build(), new StreamObserver() { @Override public void onNext(ExportAccountResponse value) { @@ -1337,7 +2282,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertEquals("accountId must be a canonical non-nil UUID", ref.get().getError().getMessage()); Mockito.verifyNoInteractions(accountService); } @@ -1373,12 +2318,14 @@ public void onCompleted() {} void deleteAccountSuccess() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + SessionContext.setContext(OTHER_ACCOUNT_UUID, List.of("platformAdmin"), Map.of()); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); AccountGrpcService service = new AccountGrpcService(pingService, accountService); AtomicReference ref = new AtomicReference<>(); service.deleteAccount( - DeleteAccountRequest.newBuilder().setAccountId("2").build(), + DeleteAccountRequest.newBuilder().setAccountId(ACCOUNT_UUID).build(), new StreamObserver() { @Override public void onNext(DeleteAccountResponse value) { @@ -1422,7 +2369,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertFalse(ref.get().getSuccess()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertEquals("accountId must be a canonical non-nil UUID", ref.get().getError().getMessage()); Mockito.verifyNoInteractions(accountService); } @@ -1430,6 +2377,8 @@ public void onCompleted() {} void linkExternalAccountSuccess() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); AccountGrpcService service = new AccountGrpcService(pingService, accountService); AtomicReference ref = @@ -1437,7 +2386,7 @@ void linkExternalAccountSuccess() { service.linkExternalAccount( net.firedevops.firemud.account.v1.LinkExternalAccountRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(ACCOUNT_UUID) .setProvider("google") .setExternalId("abc") .build(), @@ -1522,7 +2471,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertFalse(ref.get().getSuccess()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertEquals("accountId must be a canonical non-nil UUID", ref.get().getError().getMessage()); Mockito.verifyNoInteractions(accountService); } 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 76154b0392..314bc88f0b 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 @@ -455,6 +455,7 @@ void createAccountMapsSpringDataIntegrityConflict() { void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -639,6 +640,7 @@ void joinPublicProductionRejectsStillActiveBootstrapForIneligibleLifecycleState( AccountLifecycleState lifecycleState, String expectedCode) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -671,6 +673,7 @@ void joinPublicProductionRejectsStillActiveBootstrapForIneligibleLifecycleState( void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -726,6 +729,7 @@ void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembership() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -813,6 +817,7 @@ void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembers void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguous) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -895,6 +900,7 @@ void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguou void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -961,6 +967,7 @@ void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1027,6 +1034,7 @@ void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { void unboundFailedJoinReplaysOnlyAfterCurrentScopeAndAuthorityChecks() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1149,6 +1157,7 @@ void unboundFailedJoinReplaysOnlyAfterCurrentScopeAndAuthorityChecks() { void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1194,6 +1203,7 @@ void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTransition() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1305,6 +1315,7 @@ void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTrans void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1416,6 +1427,7 @@ void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { void joinPublicProductionHidesAnotherAccountsGlobalRequestIdEvidence(String originalStatus) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1514,6 +1526,7 @@ void joinPublicProductionHidesAnotherAccountsGlobalRequestIdEvidence(String orig void reclaimedScopeRaceReturnsConnectScopeInvalid() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1560,6 +1573,7 @@ void reclaimedScopeRaceReturnsConnectScopeInvalid() { void quarantinedLegacyMembershipIsNeverRestoredByPublicJoin() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1828,6 +1842,7 @@ void emailLoginOtpRequestPersistsOnlyHashedChallengeAndSendsSixDigitCode() { void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { Account account = new Account(); account.setId(9L); + setPersistedAuthenticationIdentity(account); account.setEmail("verified@example.com"); account.setEmailVerified(true); account.setRole("player"); @@ -1860,7 +1875,7 @@ void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { AuthenticationResult result = service.verifyEmailLoginOtp("verified@example.com", codeMatcher.group(1)); - assertEquals(9L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); assertNotNull(result.authToken()); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) .delete(challengeCaptor.getValue()); @@ -1876,6 +1891,7 @@ void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { Account account = new Account(); account.setId(9L); + setPersistedAuthenticationIdentity(account); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = @@ -1890,7 +1906,7 @@ void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "123456"); - assertEquals(9L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).delete(challenge); org.mockito.Mockito.verify(sessionService) .storeAccountSession(9L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); @@ -1901,6 +1917,7 @@ void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { void authenticateFallsBackToPasswordWithoutBurningUnmatchedEmailLoginOtp() { Account account = new Account(); account.setId(9L); + setPersistedAuthenticationIdentity(account); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = @@ -1915,7 +1932,7 @@ void authenticateFallsBackToPasswordWithoutBurningUnmatchedEmailLoginOtp() { AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - assertEquals(9L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) .delete(challenge); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) @@ -1965,6 +1982,57 @@ void passwordOnlyAccountsDoNotIssueEmailLoginChallenges() { accountTenantMembershipRepository, accountEmailLoginChallengeRepository, emailService); } + @ParameterizedTest + @EnumSource(AccountIdentityProvenance.class) + void gameplayAuthenticationAcceptsEveryRecognizedPersistedUuidProvenance( + AccountIdentityProvenance provenance) { + Account account = new Account(); + account.setId(31L); + account.setEmail("retained@example.com"); + account.setPasswordHash(hash("password")); + setPersistedAuthenticationIdentity(account, provenance); + when(accountRepository.findByEmail("retained@example.com")).thenReturn(Optional.of(account)); + + AuthenticationResult result = + service.authenticateForGameplay("retained@example.com", "password"); + var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); + + assertEquals(account.getAccountUuid().toString(), result.accountId()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertFalse(claims.containsKey("tenantId")); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(31L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + } + + @ParameterizedTest + @EnumSource(InvalidAuthenticationIdentity.class) + void gameplayAuthenticationRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( + InvalidAuthenticationIdentity invalidIdentity) { + Account account = new Account(); + account.setId(32L); + account.setEmail("unproved@example.com"); + assignInvalidAuthenticationIdentity(account, invalidIdentity); + var challenge = new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(8L); + challenge.setAccountId(32L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByEmail("unproved@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(32L)) + .thenReturn(Optional.of(challenge)); + + assertThrows( + IllegalStateException.class, + () -> service.authenticateForGameplay("unproved@example.com", "123456")); + + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(32L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(32L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(challenge); + verifyNoInteractions(sessionService); + } + @Test void emailLoginOtpVerificationFailsClosedForUnknownEmail() { when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); @@ -1982,6 +2050,7 @@ void emailLoginOtpVerificationFailsClosedForUnknownEmail() { void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { Account account = new Account(); account.setId(9L); + setPersistedAuthenticationIdentity(account); account.setEmail("verified@example.com"); account.setRole("player"); net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = @@ -1997,10 +2066,11 @@ void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { AuthenticationResult result = service.verifyEmailLoginOtp("verified@example.com", "123456"); - assertEquals(9L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); assertEquals("account-service", claims.getAudience().iterator().next()); - assertEquals(9L, claims.get("accountId", Long.class)); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(9L); inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(9L); @@ -2011,6 +2081,7 @@ void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { void authenticateReturnsControlUiTokenWithoutGameplayMembership() { Account account = new Account(); account.setId(1L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2018,10 +2089,11 @@ void authenticateReturnsControlUiTokenWithoutGameplayMembership() { AuthenticationResult result = service.authenticate("demo", "password"); assertNotNull(result.authToken()); - assertEquals(1L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); assertEquals("control-ui", claims.getAudience().iterator().next()); - assertEquals(1L, claims.get("accountId", Long.class)); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); assertEquals(java.util.List.of(), claims.get("globalRoles")); assertNotNull(claims.get("jti")); assertFalse(claims.containsKey("tenantId")); @@ -2056,6 +2128,7 @@ void authenticateRejectsIneligibleLifecycleState( void authenticateForGameplayReturnsTokenWhenPasswordMatches() { Account account = new Account(); account.setId(1L); + setPersistedAuthenticationIdentity(account); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); @@ -2064,10 +2137,11 @@ void authenticateForGameplayReturnsTokenWhenPasswordMatches() { AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); assertNotNull(result.authToken()); - assertEquals(1L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); assertEquals("account-service", claims.getAudience().iterator().next()); - assertEquals(1L, claims.get("accountId", Long.class)); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); assertEquals(java.util.List.of(), claims.get("globalRoles")); assertNotNull(claims.get("jti")); org.mockito.Mockito.verify(sessionService) @@ -2079,6 +2153,7 @@ void authenticateForGameplayReturnsTokenWhenPasswordMatches() { void issuePlayerBootstrapReturnsShortLivedToken() { Account account = new Account(); account.setId(7L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); account.setLoginAuthModes("PASSWORD"); @@ -2087,7 +2162,7 @@ void issuePlayerBootstrapReturnsShortLivedToken() { PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "password"); - assertEquals(7L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); assertNotNull(result.bootstrapToken()); assertNotNull(result.issuedAt()); assertNotNull(result.expiresAt()); @@ -2098,15 +2173,51 @@ void issuePlayerBootstrapReturnsShortLivedToken() { org.mockito.ArgumentMatchers.eq(300000L)); var claims = new JwtUtil(JWT_SECRET, 300000L).parseToken(result.bootstrapToken()).getPayload(); assertEquals("player-bootstrap", claims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); assertFalse(claims.containsKey("tenantId")); assertEquals(300000L, claims.getExpiration().getTime() - claims.getIssuedAt().getTime()); + when(sessionService.isAccountSessionActive(7L, result.bootstrapToken())).thenReturn(true); + var worlds = service.listBootstrapWorlds(result.bootstrapToken()); + assertEquals("demo", worlds.getFirst().worldSlug()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.times(2)) + .findByAccountUuid(account.getAccountUuid()); + org.mockito.Mockito.verify(sessionService).isAccountSessionActive(7L, result.bootstrapToken()); verifyNoInteractions(accountEmailLoginChallengeRepository); } + @ParameterizedTest + @EnumSource(InvalidAuthenticationIdentity.class) + void issuePlayerBootstrapRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( + InvalidAuthenticationIdentity invalidIdentity) { + Account account = new Account(); + account.setId(50L); + account.setUsername("demo"); + account.setLoginAuthModes("EMAIL_OTP"); + assignInvalidAuthenticationIdentity(account, invalidIdentity); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setAccountId(50L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(50L)) + .thenReturn(Optional.of(challenge)); + + assertThrows(IllegalStateException.class, () -> service.issuePlayerBootstrap("demo", "123456")); + + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(50L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(50L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(challenge); + verifyNoInteractions(sessionService); + } + @Test void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { Account emailAccount = new Account(); emailAccount.setId(7L); + setPersistedAuthenticationIdentity(emailAccount); emailAccount.setUsername("email-owner"); emailAccount.setEmail("player@example.com"); emailAccount.setPasswordHash(hash("password")); @@ -2116,7 +2227,7 @@ void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { PlayerBootstrapResult result = service.issuePlayerBootstrap(" PLAYER@EXAMPLE.COM ", "password"); - assertEquals(7L, result.accountId()); + assertEquals(emailAccount.getAccountUuid().toString(), result.accountId()); org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) .findByUsername(org.mockito.ArgumentMatchers.anyString()); } @@ -2125,6 +2236,7 @@ void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { Account account = new Account(); account.setId(7L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setEmail("demo@example.com"); account.setLoginAuthModes("EMAIL_OTP"); @@ -2139,7 +2251,7 @@ void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "123456"); - assertEquals(7L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(7L); inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(7L); @@ -2150,9 +2262,14 @@ void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { @Test void listBootstrapWorldsRejectsInactiveAccountBootstrapToken() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + String accountUuid = account.getAccountUuid().toString(); String bootstrapToken = new JwtUtil(JWT_SECRET, 300000L) - .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "11")); + .generateToken( + accountUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); AuthenticationException ex = assertThrows( @@ -2163,11 +2280,20 @@ void listBootstrapWorldsRejectsInactiveAccountBootstrapToken() { org.mockito.Mockito.verify(sessionService).isAccountSessionActive(11L, bootstrapToken); } - @Test - void listBootstrapWorldsRejectsMalformedBootstrapTokenAccountClaim() { + @ParameterizedTest + @ValueSource( + strings = { + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "4C4B57D8-E3A2-48FE-9977-E7DF0FDCE901", + " 4c4b57d8-e3a2-48fe-9977-e7df0fdce901", + "4c4b57d8-e3a2-48fe-9977-e7df0fdce901 " + }) + void listBootstrapWorldsRejectsMalformedOrNoncanonicalBootstrapAccountUuid(String accountUuid) { String malformedBootstrapToken = new JwtUtil(JWT_SECRET, 300000L) - .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "abc")); + .generateToken( + accountUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); AuthenticationException ex = assertThrows( @@ -2175,13 +2301,16 @@ void listBootstrapWorldsRejectsMalformedBootstrapTokenAccountClaim() { () -> service.listBootstrapWorlds(malformedBootstrapToken)); assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + verifyNoInteractions(accountRepository, sessionService); } @Test void listBootstrapWorldsRejectsBootstrapTokenAccountSubjectMismatch() { String malformedBootstrapToken = new JwtUtil(JWT_SECRET, 300000L) - .generateToken("12", Map.of("aud", "player-bootstrap", "accountId", "11")); + .generateToken( + REALM_ID, + Map.of("aud", "player-bootstrap", "accountId", PLAYABLE_STATE_NAMESPACE_ID)); AuthenticationException ex = assertThrows( @@ -2189,13 +2318,14 @@ void listBootstrapWorldsRejectsBootstrapTokenAccountSubjectMismatch() { () -> service.listBootstrapWorlds(malformedBootstrapToken)); assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + verifyNoInteractions(accountRepository, sessionService); } @Test - void listBootstrapWorldsRejectsNonPositiveBootstrapTokenClaims() { + void listBootstrapWorldsRejectsLegacyNumericBootstrapTokenClaims() { String malformedBootstrapToken = new JwtUtil(JWT_SECRET, 300000L) - .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "0")); + .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "11")); AuthenticationException ex = assertThrows( @@ -2267,6 +2397,7 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2306,6 +2437,7 @@ void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { void listBootstrapRealmsMapsZeroPublicAuthorityFromGameSession() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2329,6 +2461,7 @@ void listBootstrapRealmsMapsZeroPublicAuthorityFromGameSession() { void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2367,6 +2500,7 @@ void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { void listBootstrapRealmsRejectsMultipleVisiblePublicRealms() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2395,6 +2529,7 @@ void listBootstrapRealmsRejectsMultipleVisiblePublicRealms() { void listBootstrapRealmsAcceptsExactlyOneVisiblePublicRealm() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2433,6 +2568,7 @@ void bootstrapRealmDiscoveryAndDirectTextScopeIssuanceSuspendIncomingTransaction void listBootstrapRealmsDoesNotIssueScopeWhenPublicPointerBecomesPrivateBeforeFinalRead() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2468,6 +2604,7 @@ void listBootstrapRealmsDoesNotIssueScopeWhenPublicPointerBecomesPrivateBeforeFi void listBootstrapRealmsDoesNotIssueScopeWhenPointerChangesDuringDiscovery() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2503,6 +2640,7 @@ void listBootstrapRealmsDoesNotIssueScopeWhenPointerChangesDuringDiscovery() { void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2542,6 +2680,7 @@ void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { void issueConnectTokenRejectsMalformedConnectScopeId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2567,10 +2706,69 @@ void issueConnectTokenRejectsMalformedConnectScopeId() { assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); } + @Test + void issueConnectTokenRejectsNumericSignedConnectCarrierWithoutReplayMutation() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String numericConnectScopeId = + new JwtUtil(JWT_SECRET, 120000L) + .generateToken( + "11", + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", "11"), + Map.entry("tenantId", "7"), + Map.entry("realmId", REALM_ID), + Map.entry("worldSlug", "demo"), + Map.entry("realmSlug", "production"), + Map.entry("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE_ID), + Map.entry("playableStateScope", "SHARED"), + Map.entry("gameInstanceId", "44"), + Map.entry("catalogRevision", "23"), + Map.entry("pointerVersion", "17"), + Map.entry("evaluatedAt", java.time.Instant.now().toString()), + Map.entry( + "connectScopeExpiresAt", + java.time.Instant.now().plusSeconds(60).toString()), + Map.entry("jti", "numeric-account-id"))); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(numericConnectScopeId, "req-numeric-account-id"))); + + assertEquals("CONNECT_SCOPE_INVALID", exception.getCode()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .getConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyLong()); + } + @Test void issueConnectTokenRejectsBlankConnectScopeId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2600,6 +2798,7 @@ void issueConnectTokenRejectsBlankConnectScopeId() { void issueConnectTokenRejectsNonPositiveConnectScopeClaims() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2653,6 +2852,7 @@ void issueConnectTokenRejectsNonPositiveConnectScopeClaims() { void issueConnectTokenRejectsMalformedConnectScopeClaims() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2707,6 +2907,7 @@ void issueConnectTokenRejectsMalformedConnectScopeClaims() { void issueConnectTokenRejectsNoncanonicalRealmIdClaims(String realmId) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2759,6 +2960,7 @@ void issueConnectTokenRejectsNoncanonicalRealmIdClaims(String realmId) { void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2776,12 +2978,12 @@ void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { String malformedConnectScopeId = new JwtUtil(JWT_SECRET, 120000L) .generateToken( - "12", + "4d3e9d15-a02e-41db-8648-0d2c68d0f0a3", Map.of( "aud", "bootstrap-connect-scope", "accountId", - "11", + account.getAccountUuid().toString(), "tenantId", "7", "worldSlug", @@ -2812,6 +3014,7 @@ void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { void issueConnectTokenRejectsBlankWorldSlugConnectScopeClaims() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2865,6 +3068,7 @@ void issueConnectTokenRejectsBlankWorldSlugConnectScopeClaims() { void issueConnectTokenRejectsZeroPointerVersionInConnectScopeClaims() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2918,6 +3122,7 @@ void issueConnectTokenRejectsZeroPointerVersionInConnectScopeClaims() { void authenticateForGameplayUsesNormalizedEmailLookup() { Account account = new Account(); account.setId(1L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); @@ -2927,7 +3132,7 @@ void authenticateForGameplayUsesNormalizedEmailLookup() { service.authenticateForGameplay(" DEMO@example.com ", "password"); assertNotNull(result.authToken()); - assertEquals(1L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); org.mockito.Mockito.verify(sessionService) .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); verifyNoInteractions(accountTenantMembershipRepository); @@ -2962,12 +3167,13 @@ void authenticateDoesNotUseGlobalAccountFallback() { void authenticateAllowsGlobalIdentityWithoutTenantMembership() { Account account = new Account(); account.setId(7L); + setPersistedAuthenticationIdentity(account); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - assertEquals(7L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); assertNotNull(result.authToken()); org.mockito.Mockito.verify(sessionService) .storeAccountSession(7L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); @@ -2978,6 +3184,7 @@ void authenticateAllowsGlobalIdentityWithoutTenantMembership() { void getTenantMembershipForRuntimeReturnsAdmissionAllowedForExistingAccount() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); @@ -3010,6 +3217,7 @@ void getTenantMembershipForRuntimeRejectsMissingAccount() { void getTenantMembershipForRuntimeRejectsCrossTenantAccount() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); @@ -3225,6 +3433,7 @@ void issueConnectTokenDoesNotReturnCachedLegacySuccess() { private ConnectScopeFixture prepareConnectScopeForIssue() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3281,6 +3490,7 @@ private record ConnectScopeFixture(String bootstrapToken, String connectScopeId) void listBootstrapCharactersUsesEntityManagementForResolvedRealm() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3324,6 +3534,7 @@ void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( boolean membershipExists) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3371,6 +3582,7 @@ void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( void listBootstrapCharactersChecksPublicJoinPolicyBeforeReturningJoinRequired() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3407,6 +3619,7 @@ void listBootstrapCharactersClassifiesInactivePublicMembershipByJoinPolicy( String subscriptionStatus, String expectedCode) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3447,6 +3660,7 @@ void listBootstrapCharactersClassifiesInactivePublicMembershipByJoinPolicy( void listBootstrapCharactersKeepsSelectedTargetFailClosedWhenEntitlementsAreUnavailable() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3480,6 +3694,7 @@ void listBootstrapCharactersKeepsSelectedTargetFailClosedWhenEntitlementsAreUnav void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDiscovery() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3549,6 +3764,7 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3602,6 +3818,7 @@ void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { void listBootstrapCharactersSkipsMalformedUnrelatedRealm() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3651,6 +3868,7 @@ void listBootstrapCharactersSkipsMalformedUnrelatedRealm() { void listBootstrapRealmsIncludesRealmStatePolicy() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3665,6 +3883,12 @@ void listBootstrapRealmsIncludesRealmStatePolicy() { assertEquals(1, realms.size()); assertEquals(REALM_ID, realms.getFirst().realmId()); + var scopeClaims = + new JwtUtil(JWT_SECRET, 300000L) + .parseToken(realms.getFirst().connectScopeId()) + .getPayload(); + assertEquals(account.getAccountUuid().toString(), scopeClaims.getSubject()); + assertEquals(account.getAccountUuid().toString(), scopeClaims.get("accountId", String.class)); assertEquals( REALM_ID, new JwtUtil(JWT_SECRET, 300000L) @@ -3689,6 +3913,7 @@ void listBootstrapRealmsRejectsNoncanonicalPlayableStateNamespaceIdFromReachable String namespaceId) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3727,9 +3952,10 @@ void listBootstrapRealmsRejectsNoncanonicalPlayableStateNamespaceIdFromReachable } @Test - void listBootstrapRealmsReadsFreshEntitlementsOncePerTenantPerInvocation() { + void listBootstrapRealmsReadsFreshEntitlementsAndReusesVerifiedAccountIdentity() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3797,18 +4023,28 @@ void listBootstrapRealmsReadsFreshEntitlementsOncePerTenantPerInvocation() { var firstCall = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) .findByTenantId(7L); + org.mockito.Mockito.clearInvocations(accountRepository); var secondCall = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); assertEquals(2, firstCall.size()); assertEquals(2, secondCall.size()); org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) .findByTenantId(7L); + org.mockito.Mockito.verify(accountRepository).findByAccountUuid(account.getAccountUuid()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()).findById(11L); + JwtUtil tokenReader = new JwtUtil(JWT_SECRET, 3600000L); + for (var realm : secondCall) { + var claims = tokenReader.parseToken(realm.connectScopeId()).getPayload(); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + } } @Test void listBootstrapWorldsReadsFreshEntitlementsOncePerTenantPerInvocation() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3858,6 +4094,7 @@ void listBootstrapWorldsReadsFreshEntitlementsOncePerTenantPerInvocation() { void listBootstrapWorldsOmitsCanceledTenantAndFailsWhenEntitlementIsUnavailable() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3941,6 +4178,7 @@ void listBootstrapWorldsOmitsCanceledTenantAndFailsWhenEntitlementIsUnavailable( void listBootstrapRealmsPropagatesUnavailableEntitlements() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3961,6 +4199,7 @@ void listBootstrapRealmsPropagatesUnavailableEntitlements() { void listBootstrapWorldsFailsInsteadOfReturningIncompleteWorldDiscovery() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4014,6 +4253,7 @@ void listBootstrapWorldsFailsInsteadOfReturningIncompleteWorldDiscovery() { void listBootstrapRealmsRethrowsOtherAuthenticationErrors() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4055,6 +4295,7 @@ void listBootstrapRealmsRethrowsOtherAuthenticationErrors() { void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4112,6 +4353,7 @@ void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { void listBootstrapRealmsRejectsRealmWithUnknownStateScope() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4153,6 +4395,7 @@ void listBootstrapRealmsRejectsRealmWithUnknownStateScope() { void listBootstrapCharactersUsesIsolatedRealmRoster() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4228,6 +4471,7 @@ void listBootstrapCharactersUsesIsolatedRealmRoster() { void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4276,6 +4520,7 @@ void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4324,6 +4569,7 @@ void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicatesAcrossWorlds() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4422,6 +4668,7 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4497,6 +4744,7 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { void listBootstrapCharactersRejectsPathThatDoesNotMatchSignedScope() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4524,6 +4772,7 @@ void listBootstrapCharactersRejectsPathThatDoesNotMatchSignedScope() { void listBootstrapCharactersRejectsChangedCanonicalRealmId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4562,6 +4811,7 @@ void listBootstrapCharactersRejectsChangedCanonicalRealmId() { void listBootstrapRealmsExcludesNonPublicRealmWithoutGrant() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4610,6 +4860,7 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( boolean visible, boolean publicProductionRealm) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4674,6 +4925,7 @@ void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( boolean visible, boolean publicProductionRealm) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4733,6 +4985,7 @@ void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( void grantRealmAccessUpsertsRuntimeGrant() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); when(accountRealmAccessGrantRepository.findByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( @@ -4765,6 +5018,7 @@ void revokeRealmAccessUsesDurableRepositoryRevocation() { void getRealmAccessGrantForRuntimeReturnsGrantState() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); AccountRealmAccessGrant grant = new AccountRealmAccessGrant(); grant.setGrantVersion(4L); @@ -4831,6 +5085,7 @@ void grantRealmAccessReactivatesRetainedTombstoneAndAdvancesItsVersion() { void getProfileReturnsDto() { Account account = new Account(); account.setId(2L); + setPersistedAuthenticationIdentity(account); Profile profile = new Profile(); profile.setAccount(account); profile.setTenantId(1L); @@ -4838,14 +5093,30 @@ void getProfileReturnsDto() { profile.setPresenceVisibilityPolicy(ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 1L)).thenReturn(true); when(profileRepository.findByAccountIdAndTenantId(2L, 1L)).thenReturn(Optional.of(profile)); - when(profileMapper.toDto(profile)) - .thenReturn( - new net.firedevops.firemud.accountservice.dto.ProfileDto( - 1L, 1L, 2L, "demo", null, ProfilePresenceVisibilityPolicy.FRIENDS_ONLY)); + when(profileMapper.toDto(profile, account.getAccountUuid().toString())) + .thenAnswer( + invocation -> + Mappers.getMapper(ProfileMapper.class) + .toDto(profile, account.getAccountUuid().toString())); var dto = service.getProfile(1L, 2L); assertEquals("demo", dto.displayName()); + assertEquals(account.getAccountUuid().toString(), dto.accountId()); + org.mockito.Mockito.verify(accountRepository).findByAccountUuid(account.getAccountUuid()); + } + + @Test + void getProfileRefusesDifferentPrivateOwnerBeforeProjection() { + Account differentOwner = new Account(); + differentOwner.setId(3L); + Profile profile = profile(differentOwner, 1L, "private"); + when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 1L)).thenReturn(true); + when(profileRepository.findByAccountIdAndTenantId(2L, 1L)).thenReturn(Optional.of(profile)); + + assertThrows(IllegalStateException.class, () -> service.getProfile(1L, 2L)); + + verifyNoInteractions(profileMapper, notificationService); } @Test @@ -4867,29 +5138,46 @@ void listPresenceVisibilityPoliciesOmitsProfilesWithoutAPolicy() { @Test void updateProfileStoresChanges() { Profile profile = new Profile(); - profile.setAccount(new Account()); + Account account = new Account(); + account.setId(2L); + setPersistedAuthenticationIdentity(account); + profile.setAccount(account); profile.setTenantId(1L); profile.setPresenceVisibilityPolicy(ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 1L)).thenReturn(true); when(profileRepository.findByAccountIdAndTenantId(2L, 1L)).thenReturn(Optional.of(profile)); when(profileRepository.save(profile)).thenReturn(profile); - when(profileMapper.toDto(profile)) + when(profileMapper.toDto(profile, account.getAccountUuid().toString())) .thenReturn( new net.firedevops.firemud.accountservice.dto.ProfileDto( - 1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE)); + 1L, + 1L, + account.getAccountUuid().toString(), + "demo", + "bio", + ProfilePresenceVisibilityPolicy.PRIVATE)); var dto = service.updateProfile( new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( - 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE)); + 1L, + account.getAccountUuid().toString(), + "demo", + "bio", + ProfilePresenceVisibilityPolicy.PRIVATE)); assertEquals("demo", dto.displayName()); assertEquals(ProfilePresenceVisibilityPolicy.PRIVATE, profile.getPresenceVisibilityPolicy()); + assertEquals(account.getAccountUuid().toString(), dto.accountId()); + org.mockito.Mockito.verify(profileRepository).findByAccountIdAndTenantId(2L, 1L); org.mockito.Mockito.verify(notificationService).sendNotification(1L, 2L, "Profile updated"); } @Test void profileReadAndUpdateFailClosedWithoutCurrentTenantMembership() { + Account account = new Account(); + account.setId(2L); + setPersistedAuthenticationIdentity(account); when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 1L)).thenReturn(false); assertEquals( @@ -4903,7 +5191,11 @@ void profileReadAndUpdateFailClosedWithoutCurrentTenantMembership() { () -> service.updateProfile( new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( - 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE))) + 1L, + account.getAccountUuid().toString(), + "demo", + "bio", + ProfilePresenceVisibilityPolicy.PRIVATE))) .getMessage()); verifyNoInteractions(profileRepository, profileMapper, notificationService); @@ -4913,7 +5205,11 @@ void profileReadAndUpdateFailClosedWithoutCurrentTenantMembership() { void updateProfileRejectsReservedHiddenStaffPolicyBeforePersistence() { var request = new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( - 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); + 1L, + "d09f80cb-a46a-415e-8d35-c9e8068e49de", + "demo", + "bio", + ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> service.updateProfile(request)); @@ -4930,20 +5226,32 @@ void exportAccountDataIncludesProfilesAcrossTenants() { account.setAccountUuid(UUID.fromString("d09f80cb-a46a-415e-8d35-c9e8068e49de")); account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_V29_MIGRATION); account.setAccountUuidSourceNumericId(2L); + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenReturn(Optional.of(account)); account.setUsername("demo"); account.setEmail("demo@example.com"); Profile tenantOne = profile(account, 1L, "one"); Profile tenantTwo = profile(account, 2L, "two"); when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); when(profileRepository.findByAccountId(2L)).thenReturn(java.util.List.of(tenantOne, tenantTwo)); - when(profileMapper.toDto(tenantOne)) + when(profileMapper.toDto(tenantOne, account.getAccountUuid().toString())) .thenReturn( new net.firedevops.firemud.accountservice.dto.ProfileDto( - 10L, 1L, 2L, "one", null, ProfilePresenceVisibilityPolicy.FRIENDS_ONLY)); - when(profileMapper.toDto(tenantTwo)) + 10L, + 1L, + account.getAccountUuid().toString(), + "one", + null, + ProfilePresenceVisibilityPolicy.FRIENDS_ONLY)); + when(profileMapper.toDto(tenantTwo, account.getAccountUuid().toString())) .thenReturn( new net.firedevops.firemud.accountservice.dto.ProfileDto( - 20L, 2L, 2L, "two", null, ProfilePresenceVisibilityPolicy.FRIENDS_ONLY)); + 20L, + 2L, + account.getAccountUuid().toString(), + "two", + null, + ProfilePresenceVisibilityPolicy.FRIENDS_ONLY)); var export = service.exportAccountData(2L); @@ -5535,13 +5843,49 @@ void updateLoginAuthModesFailsClosedBeforeReadingOrPersistingAccount() { org.mockito.Mockito.verifyNoInteractions(accountRepository); } - private static Account directTextAccount() { + private Account directTextAccount() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); return account; } + private void setPersistedAuthenticationIdentity(Account account) { + setPersistedAuthenticationIdentity( + account, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + } + + private void setPersistedAuthenticationIdentity( + Account account, AccountIdentityProvenance provenance) { + account.setAccountUuid(UUID.randomUUID()); + account.setAccountUuidProvenance(provenance); + account.setAccountUuidSourceNumericId(account.getId()); + when(accountRepository.findById(account.getId())).thenReturn(Optional.of(account)); + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenReturn(Optional.of(account)); + } + + private void assignInvalidAuthenticationIdentity( + Account account, InvalidAuthenticationIdentity failure) { + setPersistedAuthenticationIdentity(account); + switch (failure) { + case MISSING_UUID -> account.setAccountUuid(null); + case NIL_UUID -> account.setAccountUuid(new UUID(0L, 0L)); + case MISSING_PROVENANCE -> account.setAccountUuidProvenance(null); + case MISSING_SOURCE_ROW -> account.setAccountUuidSourceNumericId(null); + case CONTRADICTORY_SOURCE_ROW -> account.setAccountUuidSourceNumericId(33L); + } + } + + private enum InvalidAuthenticationIdentity { + MISSING_UUID, + NIL_UUID, + MISSING_PROVENANCE, + MISSING_SOURCE_ROW, + CONTRADICTORY_SOURCE_ROW + } + private static DirectTextCallerContext directTextCaller() { return new DirectTextCallerContext( 11L, diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java index 31b1d7f0d0..af99f44bb5 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java @@ -798,7 +798,14 @@ private TriggerAdmission validateDryRunBudget( if (!request.getIsDryRun()) { return null; } - String principalKey = dryRunPrincipalKey(); + final String principalKey; + try { + principalKey = dryRunPrincipalKey(); + } catch (IllegalArgumentException ex) { + // A malformed Account subject is a permanent principal-validation failure. Keep it in the + // claimed event's normal finalization path so retries converge on a bounded denial. + return new TriggerAdmission(false, OUTCOME_REGISTRY_REJECTED, "dry_run_principal_invalid", 0); + } if (principalKey.isBlank()) { return new TriggerAdmission(false, OUTCOME_QUOTA_DENIED, "dry_run_principal_missing", 0); } @@ -1611,9 +1618,9 @@ private static String resolveSourceService() { } private static String dryRunPrincipalKey() { - Long accountId = SessionContext.currentAccountIdOrNull(); - if (accountId != null) { - return "account:" + accountId; + String accountUuid = SessionContext.currentAccountUuidOrNull(); + if (accountUuid != null) { + return "account:" + accountUuid; } String serviceName = SessionContext.getServiceName(); if (serviceName != null && !serviceName.isBlank()) { diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java index 7ba9937a36..ea59e034e5 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java @@ -3182,7 +3182,12 @@ void quotaDeniedHandlerWritesAuditWithoutWorkItem() { @Test void dryRunBudgetDenialStopsBeforeHandlerResolution() { SessionContext.setContext( - "41", List.of("platformAdmin"), Map.of(), true, "game-session-service", "gs-1"); + "11111111-1111-1111-1111-111111111111", + List.of("platformAdmin"), + Map.of(), + true, + "game-session-service", + "gs-1"); ScriptEventIngressAuditRepository repository = Mockito.mock(ScriptEventIngressAuditRepository.class); stubClaimRepository(repository); @@ -3202,7 +3207,9 @@ void dryRunBudgetDenialStopsBeforeHandlerResolution() { .setScriptPatchPinnedControlPlaneRequestId("pin-request-1") .build()) .build()); - when(dryRunQuotaService.tryAcquire("1", "script-1", "account:41")).thenReturn(false); + when(dryRunQuotaService.tryAcquire( + "1", "script-1", "account:11111111-1111-1111-1111-111111111111")) + .thenReturn(false); ScriptEventBindingRepository bindingRepository = Mockito.mock(ScriptEventBindingRepository.class); ScriptEventIngressService service = @@ -3244,6 +3251,8 @@ void dryRunBudgetDenialStopsBeforeHandlerResolution() { assertThat(admission.outcome()) .isEqualTo(TriggerAdmissionOutcome.TRIGGER_ADMISSION_OUTCOME_QUOTA_DENIED.name()); assertThat(admission.reason()).isEqualTo("dry_run_budget_exceeded"); + verify(dryRunQuotaService) + .tryAcquire("1", "script-1", "account:11111111-1111-1111-1111-111111111111"); verify(bindingRepository, never()) .findByTenantIdAndScriptPatchVersionAndEventTypeAndEventSchemaVersionAndEnabledTrueOrderByPriorityAscScriptIdAsc( Mockito.anyLong(), @@ -3253,9 +3262,18 @@ void dryRunBudgetDenialStopsBeforeHandlerResolution() { Mockito.anyString()); } - @Test - void dryRunRejectsMalformedCurrentAccountClaimBeforeQuotaLookup() { - SessionContext.setContext("not-a-long", List.of(), Map.of()); + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource( + strings = { + "42", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "B8D093F7-CB70-40ED-9FAC-3C82D4BF28F1", + " b8d093f7-cb70-40ed-9fac-3c82d4bf28f1 " + }) + void dryRunPersistsRejectionForMalformedCurrentAccountClaimBeforeQuotaLookup(String account) { + SessionContext.setContext( + account, List.of(), Map.of(), true, "game-session-service", "game-session-1"); ScriptEventIngressAuditRepository repository = Mockito.mock(ScriptEventIngressAuditRepository.class); stubClaimRepository(repository); @@ -3277,12 +3295,15 @@ void dryRunRejectsMalformedCurrentAccountClaimBeforeQuotaLookup() { .build()); ScriptEventBindingRepository bindingRepository = Mockito.mock(ScriptEventBindingRepository.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository eventAuditRepository = + Mockito.mock(ScriptEventAuditRepository.class); ScriptEventIngressService service = new ScriptEventIngressServiceImpl( repository, bindingRepository, - Mockito.mock(ScriptWorkItemRepository.class), - Mockito.mock(ScriptEventAuditRepository.class), + workItemRepository, + eventAuditRepository, new BuiltInScriptEventRegistryService(), Mockito.mock(AutomationQueueService.class), outputProperties(), @@ -3295,27 +3316,40 @@ void dryRunRejectsMalformedCurrentAccountClaimBeforeQuotaLookup() { allowingQuotaService(), dryRunQuotaService); - assertThrows( - IllegalArgumentException.class, - () -> - service.admit( - gameplayRequestBuilder() - .setTenantId("1") - .setGameInstanceId("game-1") - .setRegionId("region-1") - .setRegionEpoch(7) - .setEntityId("entity-1") - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .setScriptId("script-1") - .setEventType("onCommand") - .setScriptPatchVersion("patch-1") - .setScriptEventId("event-dry-run-invalid-account") - .setReadSnapshotToken("snapshot-1") - .setIsDryRun(true) - .build(), - "game-session-service")); + ScriptEventIngressService.TriggerAdmission admission = + service.admit( + gameplayRequestBuilder() + .setTenantId("1") + .setGameInstanceId("game-1") + .setRegionId("region-1") + .setRegionEpoch(7) + .setEntityId("entity-1") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setScriptId("script-1") + .setEventType("onCommand") + .setScriptPatchVersion("patch-1") + .setScriptEventId("event-dry-run-invalid-account") + .setReadSnapshotToken("snapshot-1") + .setIsDryRun(true) + .build(), + "game-session-service"); + assertThat(admission.admitted()).isFalse(); + assertThat(admission.outcome()) + .isEqualTo( + TriggerAdmissionOutcome.TRIGGER_ADMISSION_OUTCOME_EVENT_REGISTRY_REJECTED.name()); + assertThat(admission.reason()).isEqualTo("dry_run_principal_invalid"); + ArgumentCaptor auditCaptor = + ArgumentCaptor.forClass(ScriptEventIngressAudit.class); + verify(repository).save(auditCaptor.capture()); + assertThat(auditCaptor.getValue().isAdmitted()).isFalse(); + assertThat(auditCaptor.getValue().getAdmissionOutcome()) + .isEqualTo( + TriggerAdmissionOutcome.TRIGGER_ADMISSION_OUTCOME_EVENT_REGISTRY_REJECTED.name()); + assertThat(auditCaptor.getValue().getAdmissionReason()).isEqualTo("dry_run_principal_invalid"); + assertThat(auditCaptor.getValue().getSourceState()).isEqualTo("TRIGGER_REJECTED"); verifyNoInteractions(dryRunQuotaService); + verifyNoInteractions(workItemRepository, eventAuditRepository); verify(bindingRepository, never()) .findByTenantIdAndScriptPatchVersionAndEventTypeAndEventSchemaVersionAndEnabledTrueOrderByPriorityAscScriptIdAsc( Mockito.anyLong(), diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java index 3a88de579d..6f952f4a28 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java @@ -89,7 +89,10 @@ public GameplaySessionAttestationClaims requireValid(String token) { String attestationType = requireClaim(claims, "attestationType"); String tenantId = requireClaim(claims, "tenantId"); String sessionId = requireClaim(claims, "sessionId"); - String accountId = requireClaim(claims, "accountId"); + String accountId = + GAMEPLAY_SESSION.equals(attestationType) + ? requireCanonicalAccountUuid(claims.get("accountId"), "accountId") + : requireClaim(claims, "accountId"); String characterId = requireClaim(claims, "characterId"); String gameInstanceId = requireClaim(claims, "gameInstanceId"); String roomInstanceId = @@ -166,13 +169,15 @@ public void requireGameplaySessionMatch( } requirePositiveId(claims.tenantId(), "tenantId"); requirePositiveId(claims.sessionId(), "sessionId"); - requirePositiveId(claims.accountId(), "accountId"); + String accountUuid = requireCanonicalAccountUuid(claims.accountId(), "accountId"); requirePositiveId(claims.characterId(), "characterId"); requirePositiveId(claims.gameInstanceId(), "gameInstanceId"); requirePositiveId(claims.pointerVersion(), "pointerVersion"); requirePositiveEquals(claims.tenantId(), tenantId, "tenantId"); requireOptionalPositiveEquals(claims.sessionId(), sessionId, "sessionId"); - requireOptionalPositiveEquals(claims.accountId(), accountId, "accountId"); + if (StringUtils.hasText(accountId)) { + requireEquals(accountUuid, requireCanonicalAccountUuid(accountId, "accountId"), "accountId"); + } requireOptionalPositiveEquals(claims.characterId(), characterId, "characterId"); requireOptionalPositiveEquals(claims.gameInstanceId(), gameInstanceId, "gameInstanceId"); // roomInstanceId remains a routed room identifier string; keep text equality here. @@ -245,6 +250,15 @@ private long requirePositiveId(String value, String fieldName) { } } + private String requireCanonicalAccountUuid(Object value, String fieldName) { + try { + return JwtClaims.requireCanonicalAccountUuid(value, fieldName); + } catch (IllegalArgumentException ex) { + throw new GameplaySessionAttestationException( + "SESSION_ATTESTATION_INVALID", ex.getMessage(), ex); + } + } + private String requireClaim(Claims claims, String name) { try { return JwtClaims.requireClaim(claims, name); diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcClientAuth.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcClientAuth.java index b39011f625..5e492c7aee 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcClientAuth.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcClientAuth.java @@ -53,14 +53,14 @@ public void start(Listener responseListener, Metadata headers) { } static String createBearerToken(JwtUtil jwtUtil, RuntimeIdentity runtimeIdentity) { - Long accountId = SessionContext.currentAccountIdOrNull(); + String accountId = SessionContext.getAccountId(); List globalRoles = SessionContext.getGlobalRoles(); Map> scopedRoles = SessionContext.getScopedRolesMap(); - if (accountId == null) { + if (accountId == null || accountId.isBlank()) { return createInternalBearerToken(jwtUtil, runtimeIdentity); } - String accountIdText = Long.toString(accountId); + String accountIdText = JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); Map claims = new HashMap<>(); claims.put("accountId", accountIdText); claims.put("globalRoles", globalRoles == null ? List.of() : globalRoles); diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java index adec1fad6a..0a9b3fefdd 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.security; import io.jsonwebtoken.Claims; +import java.util.UUID; import org.springframework.util.StringUtils; /** Shared helpers for canonical JWT claim extraction and normalization. */ @@ -33,19 +34,36 @@ public static long requireLong(Object value, String claimName, boolean allowZero return parsed; } - public static long requireSignedActorAccountId(Claims claims, String mismatchMessage) { - long subjectAccountId = requireLong(claims.getSubject(), "sub", false); - long claimedAccountId = requireLong(claims.get("accountId"), "accountId", false); - if (subjectAccountId != claimedAccountId) { + public static String requireCanonicalAccountUuid(Object value, String claimName) { + if (!(value instanceof String text) + || !StringUtils.hasText(text) + || !text.equals(text.trim())) { + throw new IllegalArgumentException("Malformed claim: " + claimName); + } + try { + UUID accountUuid = UUID.fromString(text); + if (!accountUuid.toString().equals(text) || accountUuid.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Invalid claim: " + claimName); + } + return text; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("Malformed claim: " + claimName, ex); + } + } + + public static String requireSignedGameplayAccountUuid(Claims claims, String mismatchMessage) { + String subjectAccountUuid = requireCanonicalAccountUuid(claims.getSubject(), "sub"); + String claimedAccountUuid = requireCanonicalAccountUuid(claims.get("accountId"), "accountId"); + if (!subjectAccountUuid.equals(claimedAccountUuid)) { throw new IllegalArgumentException(mismatchMessage); } - return claimedAccountId; + return claimedAccountUuid; } public static SignedGameplayRoutingClaims requireSignedGameplayRoutingClaims( Claims claims, String accountMismatchMessage) { return new SignedGameplayRoutingClaims( - requireSignedActorAccountId(claims, accountMismatchMessage), + requireSignedGameplayAccountUuid(claims, accountMismatchMessage), requireLong(claims.get("tenantId"), "tenantId", false), requireText(claims.get("worldSlug"), "worldSlug"), requireText(claims.get("realmSlug"), "realmSlug"), @@ -80,7 +98,7 @@ private static String firstNonBlank(Iterable values) { } public record SignedGameplayRoutingClaims( - long accountId, + String accountId, long tenantId, String worldSlug, String realmSlug, diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java index 9be0d460e1..87381a7bac 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java @@ -29,11 +29,20 @@ public record SessionClaims( public static SessionClaims fromJwt(Jws jwt) { Claims payload = jwt.getPayload(); + boolean internalService = Boolean.TRUE.equals(payload.get("internalService", Boolean.class)); + String accountId = ""; + if (!internalService || payload.containsKey("accountId")) { + accountId = JwtClaims.requireCanonicalAccountUuid(payload.get("accountId"), "accountId"); + String subject = JwtClaims.requireCanonicalAccountUuid(payload.get("sub"), "sub"); + if (!accountId.equals(subject)) { + throw new IllegalArgumentException("Account subject does not match accountId"); + } + } return new SessionClaims( - JwtClaims.claimText(payload.get("accountId")), + accountId, extractGlobalRoles(payload.get("globalRoles")), extractScopedRoles(payload.get("scopedRoles")), - Boolean.TRUE.equals(payload.get("internalService", Boolean.class)), + internalService, JwtClaims.claimText(payload.get("serviceName")), JwtClaims.claimText(payload.get("serviceInstanceId"))); } diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java index 5383df3e6f..6a5168858d 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java @@ -107,16 +107,16 @@ public static boolean hasAuthenticatedCallerContext() { } /** - * Returns the current account id when present. + * Returns the current canonical Account UUID when present. * - *

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

Blank or missing claims return {@code null}. Malformed, nil, or non-UUID claims fail closed. */ - public static Long currentAccountIdOrNull() { + public static String currentAccountUuidOrNull() { ClaimsData data = currentData(); if (data == null || data.accountId == null || data.accountId.isBlank()) { return null; } - return JwtClaims.requireLong(data.accountId, "accountId", false); + return JwtClaims.requireCanonicalAccountUuid(data.accountId, "accountId"); } /** Throws 403 when the current caller cannot act on the provided tenant. */ diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java index dd54a8783c..3a09bf100d 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java @@ -10,6 +10,8 @@ class GameplaySessionAttestationServiceTest { + private static final String ACCOUNT_UUID = "4a2df976-17b8-4c41-8d39-afe974913c16"; + private final JwtUtil jwtUtil; private final GameplaySessionAttestationService service; @@ -18,11 +20,37 @@ class GameplaySessionAttestationServiceTest { service = new GameplaySessionAttestationService(jwtUtil); } + @Test + void requireGameplaySessionMatchAcceptsCanonicalNonNilAccountUuid() { + String token = + service.issueGameplaySessionAttestation( + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + + assertDoesNotThrow( + () -> + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); + } + + @Test + void requireGameplaySessionMatchRejectsNumericMalformedNoncanonicalAndNilAccountClaims() { + assertInvalidAccountIdClaim(7, "Malformed claim: accountId"); + assertInvalidAccountIdClaim("7", "Malformed claim: accountId"); + assertInvalidAccountIdClaim("not-a-uuid", "Malformed claim: accountId"); + assertInvalidAccountIdClaim(List.of(ACCOUNT_UUID), "Malformed claim: accountId"); + assertInvalidAccountIdClaim(Map.of("id", ACCOUNT_UUID), "Malformed claim: accountId"); + assertInvalidAccountIdClaim(" " + ACCOUNT_UUID, "Malformed claim: accountId"); + assertInvalidAccountIdClaim( + ACCOUNT_UUID.toUpperCase(java.util.Locale.ROOT), "Malformed claim: accountId"); + assertInvalidAccountIdClaim( + "00000000-0000-0000-0000-000000000000", "Malformed claim: accountId"); + } + @Test void requireGameplaySessionMatchAllowsOmittedOptionalDimensions() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); assertDoesNotThrow( () -> service.requireGameplaySessionMatch(token, "22", null, null, "123", "1", "R-1021")); @@ -32,13 +60,20 @@ void requireGameplaySessionMatchAllowsOmittedOptionalDimensions() { void requireGameplaySessionMatchStillRejectsProvidedMismatchedDimensions() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); GameplaySessionAttestationException ex = assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "99", "123", "1", "R-1021")); + service.requireGameplaySessionMatch( + token, + "22", + "41", + "78947a2b-1da8-4663-adb1-718fe4ff79aa", + "123", + "1", + "R-1021")); assertEquals("SESSION_ATTESTATION_MISMATCH", ex.getCode()); assertEquals("Gameplay session attestation does not match accountId", ex.getMessage()); @@ -48,23 +83,26 @@ void requireGameplaySessionMatchStillRejectsProvidedMismatchedDimensions() { void requireGameplaySessionMatchAllowsAlphanumericRoomInstanceId() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); assertDoesNotThrow( - () -> service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-1021")); + () -> + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); } @Test void requireGameplaySessionMatchRejectsMismatchedAlphanumericRoomInstanceId() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); GameplaySessionAttestationException ex = assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-2045")); + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-2045")); assertEquals("SESSION_ATTESTATION_MISMATCH", ex.getCode()); assertEquals("Gameplay session attestation does not match roomInstanceId", ex.getMessage()); @@ -79,7 +117,7 @@ void requireGameplaySessionMatchRejectsLegacyRuntimeRoomIdClaim() { Map.entry("attestationType", "GAMEPLAY_SESSION"), Map.entry("tenantId", "22"), Map.entry("sessionId", "41"), - Map.entry("accountId", "7"), + Map.entry("accountId", ACCOUNT_UUID), Map.entry("characterId", "123"), Map.entry("gameInstanceId", "1"), Map.entry("roomInstanceId", "room-1021"), @@ -92,7 +130,8 @@ void requireGameplaySessionMatchRejectsLegacyRuntimeRoomIdClaim() { assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-1021")); + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); assertEquals("roomInstanceId must be a runtime room id like R-1021", ex.getMessage()); @@ -102,7 +141,7 @@ void requireGameplaySessionMatchRejectsLegacyRuntimeRoomIdClaim() { void requireGameplaySessionMatchRejectsMismatchedAttestedRoutingScope() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); GameplaySessionAttestationException ex = assertThrows( @@ -112,7 +151,7 @@ void requireGameplaySessionMatchRejectsMismatchedAttestedRoutingScope() { token, "22", "41", - "7", + ACCOUNT_UUID, "123", "1", "R-1021", @@ -129,12 +168,14 @@ void requireGameplaySessionMatchRejectsMismatchedAttestedRoutingScope() { void requireGameplaySessionMatchRejectsZeroTenantIdClaim() { String token = service.issueGameplaySessionAttestation( - "0", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "0", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); GameplaySessionAttestationException ex = assertThrows( GameplaySessionAttestationException.class, - () -> service.requireGameplaySessionMatch(token, "0", "41", "7", "123", "1", "R-1021")); + () -> + service.requireGameplaySessionMatch( + token, "0", "41", ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); assertEquals("Invalid claim: tenantId", ex.getMessage()); @@ -144,13 +185,14 @@ void requireGameplaySessionMatchRejectsZeroTenantIdClaim() { void requireGameplaySessionMatchRejectsZeroPointerVersionClaim() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "0", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "0", "SHARED"); GameplaySessionAttestationException ex = assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-1021")); + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); assertEquals("Invalid claim: pointerVersion", ex.getMessage()); @@ -165,7 +207,7 @@ void requireGameplaySessionMatchRejectsNonNumericClaimId() { Map.entry("attestationType", "GAMEPLAY_SESSION"), Map.entry("tenantId", "22"), Map.entry("sessionId", "41"), - Map.entry("accountId", "7"), + Map.entry("accountId", ACCOUNT_UUID), Map.entry("characterId", "abc"), Map.entry("gameInstanceId", "1"), Map.entry("roomInstanceId", "R-1021"), @@ -178,7 +220,8 @@ void requireGameplaySessionMatchRejectsNonNumericClaimId() { assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-1021")); + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); assertEquals("Malformed claim: characterId", ex.getMessage()); @@ -193,7 +236,7 @@ void requireGameplaySessionMatchRejectsSubjectClaimMismatch() { Map.entry("attestationType", "GAMEPLAY_SESSION"), Map.entry("tenantId", "22"), Map.entry("sessionId", "41"), - Map.entry("accountId", "7"), + Map.entry("accountId", ACCOUNT_UUID), Map.entry("characterId", "123"), Map.entry("gameInstanceId", "1"), Map.entry("roomInstanceId", "R-1021"), @@ -206,26 +249,57 @@ void requireGameplaySessionMatchRejectsSubjectClaimMismatch() { assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", "41", "7", "123", "1", "R-1021")); + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); assertEquals("Gameplay session attestation subject does not match claims", ex.getMessage()); } @Test - void requireGameplaySessionMatchRejectsNonPositiveExpectedAccountId() { + void requireGameplaySessionMatchRejectsNumericExpectedAccountId() { String token = service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED"); + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); GameplaySessionAttestationException ex = assertThrows( GameplaySessionAttestationException.class, () -> - service.requireGameplaySessionMatch(token, "22", null, "0", "123", "1", "R-1021")); + service.requireGameplaySessionMatch(token, "22", null, "7", "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); - assertEquals("Invalid claim: accountId", ex.getMessage()); + assertEquals("Malformed claim: accountId", ex.getMessage()); + } + + private void assertInvalidAccountIdClaim(Object accountId, String expectedMessage) { + String token = tokenWithAccountId(accountId); + GameplaySessionAttestationException ex = + assertThrows( + GameplaySessionAttestationException.class, + () -> + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); + + assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); + assertEquals(expectedMessage, ex.getMessage()); + } + + private String tokenWithAccountId(Object accountId) { + return jwtUtil.generateToken( + "gameplay-session:41", + Map.ofEntries( + Map.entry("attestationType", "GAMEPLAY_SESSION"), + Map.entry("tenantId", "22"), + Map.entry("sessionId", "41"), + Map.entry("accountId", accountId), + Map.entry("characterId", "123"), + Map.entry("gameInstanceId", "1"), + Map.entry("roomInstanceId", "R-1021"), + Map.entry("worldSlug", "demo"), + Map.entry("realmSlug", "production"), + Map.entry("pointerVersion", "17"), + Map.entry("playableStateScope", "SHARED"))); } @Test @@ -331,7 +405,7 @@ void issueGameplaySessionAttestationRejectsLegacyRuntimeRoomId() { service.issueGameplaySessionAttestation( "22", "41", - "7", + ACCOUNT_UUID, "123", "1", "room-1021", @@ -371,7 +445,16 @@ void requireAdmittedRoutingBundleAcceptsGameplayAttestationWithRoutingClaims() { GameplaySessionAttestationClaims claims = service.requireValid( service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", "demo", "production", "17", "SHARED")); + "22", + "41", + ACCOUNT_UUID, + "123", + "1", + "R-1021", + "demo", + "production", + "17", + "SHARED")); assertDoesNotThrow(() -> service.requireAdmittedRoutingBundle(claims)); } @@ -386,7 +469,7 @@ void requireAdmittedRoutingBundleRejectsGameplayAttestationMissingPointerVersion Map.entry("attestationType", "GAMEPLAY_SESSION"), Map.entry("tenantId", "22"), Map.entry("sessionId", "41"), - Map.entry("accountId", "7"), + Map.entry("accountId", ACCOUNT_UUID), Map.entry("characterId", "123"), Map.entry("gameInstanceId", "1"), Map.entry("roomInstanceId", "R-1021"), @@ -411,7 +494,16 @@ void issueGameplaySessionAttestationRejectsMissingRoutingBundleClaims() { IllegalArgumentException.class, () -> service.issueGameplaySessionAttestation( - "22", "41", "7", "123", "1", "R-1021", null, "production", null, "SHARED")); + "22", + "41", + ACCOUNT_UUID, + "123", + "1", + "R-1021", + null, + "production", + null, + "SHARED")); assertEquals("worldSlug must not be blank", ex.getMessage()); } @@ -425,7 +517,7 @@ void requireValidUsesCanonicalIterableClaimParsing() { Map.entry("attestationType", "GAMEPLAY_SESSION"), Map.entry("tenantId", List.of(" ", "22")), Map.entry("sessionId", "41"), - Map.entry("accountId", "7"), + Map.entry("accountId", ACCOUNT_UUID), Map.entry("characterId", "123"), Map.entry("gameInstanceId", "1"), Map.entry("roomInstanceId", List.of("", "R-1021")), diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GrpcClientAuthTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GrpcClientAuthTest.java index 31140c22c0..ddcd76ae07 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GrpcClientAuthTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GrpcClientAuthTest.java @@ -19,6 +19,8 @@ import org.junit.jupiter.api.Test; class GrpcClientAuthTest { + private static final String ACCOUNT_UUID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + private static final String OTHER_ACCOUNT_UUID = "4d3e9d15-a02e-41db-8648-0d2c68d0f0a3"; private static final Metadata.Key AUTH_HEADER = Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER); @@ -38,15 +40,18 @@ void attachUsesCurrentSessionContextPerCall() { TestStub stub = new TestStub(channel, CallOptions.DEFAULT); TestStub customized = GrpcClientAuth.attach(stub, jwtUtil, runtimeIdentity); - SessionContext.setContext("1", List.of("player"), Map.of()); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); customized.invoke(); String firstToken = bearerToken(channel.lastAuthorization()); - assertThat(jwtUtil.parseToken(firstToken).getPayload().getSubject()).isEqualTo("1"); + assertThat(jwtUtil.parseToken(firstToken).getPayload().getSubject()).isEqualTo(ACCOUNT_UUID); + assertThat(jwtUtil.parseToken(firstToken).getPayload().get("accountId")) + .isEqualTo(ACCOUNT_UUID); - SessionContext.setContext("2", List.of("player"), Map.of()); + SessionContext.setContext(OTHER_ACCOUNT_UUID, List.of("player"), Map.of()); customized.invoke(); String secondToken = bearerToken(channel.lastAuthorization()); - assertThat(jwtUtil.parseToken(secondToken).getPayload().getSubject()).isEqualTo("2"); + assertThat(jwtUtil.parseToken(secondToken).getPayload().getSubject()) + .isEqualTo(OTHER_ACCOUNT_UUID); assertThat(secondToken).isNotEqualTo(firstToken); } @@ -77,7 +82,19 @@ void attachRejectsMalformedCurrentAccountClaim() { TestStub stub = new TestStub(channel, CallOptions.DEFAULT); TestStub customized = GrpcClientAuth.attach(stub, jwtUtil, runtimeIdentity); - SessionContext.setContext("not-a-long", List.of("player"), Map.of()); + SessionContext.setContext("not-a-uuid", List.of("player"), Map.of()); + + assertThrows(IllegalArgumentException.class, customized::invoke); + assertThat(channel.lastAuthorization()).isNull(); + } + + @Test + void attachRejectsNumericCurrentAccountClaim() { + CapturingChannel channel = new CapturingChannel(); + TestStub stub = new TestStub(channel, CallOptions.DEFAULT); + TestStub customized = GrpcClientAuth.attach(stub, jwtUtil, runtimeIdentity); + + SessionContext.setContext("42", List.of("player"), Map.of()); assertThrows(IllegalArgumentException.class, customized::invoke); assertThat(channel.lastAuthorization()).isNull(); diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java index 3097b0f1b7..ee682b0e38 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java @@ -1,13 +1,113 @@ package net.firedevops.firemud.common.security; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jws; import java.util.List; import java.util.Map; +import java.util.UUID; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; class SessionClaimsTest { + private static final String ACCOUNT_ID = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; + + @Test + void fromJwtPreservesCanonicalSignedAccountIdentityAndRoles() { + Claims payload = mock(Claims.class); + when(payload.get("accountId")).thenReturn(ACCOUNT_ID); + when(payload.get("sub")).thenReturn(ACCOUNT_ID); + when(payload.get("globalRoles")).thenReturn(List.of("platformAdmin")); + when(payload.get("scopedRoles")).thenReturn(Map.of("7", List.of("moderator"))); + + SessionClaims claims = SessionClaims.fromJwt(jwt(payload)); + + assertEquals(ACCOUNT_ID, claims.accountId()); + assertEquals(List.of("platformAdmin"), claims.globalRoles()); + assertEquals(Map.of("7", List.of("moderator")), claims.scopedRoles()); + assertFalse(claims.internalService()); + } + + @ParameterizedTest + @MethodSource("malformedAccountIdentityClaims") + void fromJwtRejectsMalformedRawAccountIdentity(String claimName, Object value) { + Claims payload = mock(Claims.class); + when(payload.get("accountId")).thenReturn(ACCOUNT_ID); + when(payload.get("sub")).thenReturn(ACCOUNT_ID); + when(payload.get(claimName)).thenReturn(value); + + assertThrows(IllegalArgumentException.class, () -> SessionClaims.fromJwt(jwt(payload))); + } + + private static Stream malformedAccountIdentityClaims() { + return Stream.of( + null, + "", + "42", + 42L, + UUID.fromString(ACCOUNT_ID), + "00000000-0000-0000-0000-000000000000", + ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT), + "1-1-1-1-1", + " " + ACCOUNT_ID, + ACCOUNT_ID + " ", + List.of(ACCOUNT_ID), + new String[] {ACCOUNT_ID}, + Map.of("value", ACCOUNT_ID)) + .flatMap(value -> Stream.of(Arguments.of("accountId", value), Arguments.of("sub", value))); + } + + @Test + void fromJwtRejectsDifferentCanonicalSignedSubject() { + Claims payload = mock(Claims.class); + when(payload.get("accountId")).thenReturn(ACCOUNT_ID); + when(payload.get("sub")).thenReturn("018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f"); + + assertThrows(IllegalArgumentException.class, () -> SessionClaims.fromJwt(jwt(payload))); + } + + @Test + void fromJwtPreservesInternalServiceWithoutAccountIdentity() { + Claims payload = mock(Claims.class); + when(payload.get("internalService", Boolean.class)).thenReturn(true); + when(payload.get("sub")).thenReturn("service:game-logic-service"); + when(payload.get("serviceName")).thenReturn("game-logic-service"); + when(payload.get("serviceInstanceId")).thenReturn("game-logic-service-1"); + + SessionClaims claims = SessionClaims.fromJwt(jwt(payload)); + + assertEquals("", claims.accountId()); + assertTrue(claims.internalService()); + assertEquals("game-logic-service", claims.serviceName()); + assertEquals("game-logic-service-1", claims.serviceInstanceId()); + } + + @Test + void internalServiceFlagDoesNotBypassPresentAccountIdentityValidation() { + Claims payload = mock(Claims.class); + when(payload.get("internalService", Boolean.class)).thenReturn(true); + when(payload.containsKey("accountId")).thenReturn(true); + when(payload.get("accountId")).thenReturn(List.of(ACCOUNT_ID)); + when(payload.get("sub")).thenReturn("service:game-logic-service"); + + assertThrows(IllegalArgumentException.class, () -> SessionClaims.fromJwt(jwt(payload))); + } + + private static Jws jwt(Claims payload) { + @SuppressWarnings("unchecked") + Jws jwt = mock(Jws.class); + when(jwt.getPayload()).thenReturn(payload); + return jwt; + } @Test void hasGameplayElevatedRoleRecognizesGlobalGodAndScopedModerator() { diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionContextTenantAccessTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionContextTenantAccessTest.java index 9ae1889a51..0b2d2f7ab8 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionContextTenantAccessTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionContextTenantAccessTest.java @@ -68,28 +68,32 @@ void currentAccountAccessRejectsNonPositiveCurrentAccountClaim() { } @Test - void currentAccountIdOrNullReturnsParsedAccountId() { - SessionContext.setContext("42", List.of(), Map.of()); + void currentAccountUuidOrNullReturnsCanonicalAccountUuid() { + String accountUuid = "11111111-1111-1111-1111-111111111111"; + SessionContext.setContext(accountUuid, List.of(), Map.of()); - assertTrue(SessionContext.currentAccountIdOrNull() == 42L); + assertTrue(accountUuid.equals(SessionContext.currentAccountUuidOrNull())); } @Test - void currentAccountIdOrNullReturnsNullWhenClaimMissing() { + void currentAccountUuidOrNullReturnsNullWhenClaimMissing() { SessionContext.clear(); - assertNull(SessionContext.currentAccountIdOrNull()); + assertNull(SessionContext.currentAccountUuidOrNull()); SessionContext.setContext(" ", List.of(), Map.of()); - assertNull(SessionContext.currentAccountIdOrNull()); + assertNull(SessionContext.currentAccountUuidOrNull()); } @Test - void currentAccountIdOrNullRejectsMalformedOrNonPositiveClaim() { + void currentAccountUuidOrNullRejectsMalformedNumericAndNilClaims() { SessionContext.setContext("not-a-long", List.of(), Map.of()); - assertThrows(IllegalArgumentException.class, SessionContext::currentAccountIdOrNull); + assertThrows(IllegalArgumentException.class, SessionContext::currentAccountUuidOrNull); - SessionContext.setContext("0", List.of(), Map.of()); - assertThrows(IllegalArgumentException.class, SessionContext::currentAccountIdOrNull); + SessionContext.setContext("42", List.of(), Map.of()); + assertThrows(IllegalArgumentException.class, SessionContext::currentAccountUuidOrNull); + + SessionContext.setContext("00000000-0000-0000-0000-000000000000", List.of(), Map.of()); + assertThrows(IllegalArgumentException.class, SessionContext::currentAccountUuidOrNull); } @Test diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java index c0bd131abf..8ccfd93c43 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java @@ -18,15 +18,20 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Stream; import net.firedevops.firemud.common.security.AuthTokenInterceptor; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.security.SessionContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; class AuthTokenInterceptorTest { + private static final String ACCOUNT_ID = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; private static final Metadata.Key AUTH_HEADER = Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER); private static final MethodDescriptor METHOD = @@ -57,9 +62,9 @@ void rejectsMalformedJwtClaims() { Metadata headers = new Metadata(); String token = jwtUtil.generateToken( - "account", + ACCOUNT_ID, Map.of( - "accountId", "account", "globalRoles", "platformAdmin", "scopedRoles", Map.of())); + "accountId", ACCOUNT_ID, "globalRoles", "platformAdmin", "scopedRoles", Map.of())); headers.put(AUTH_HEADER, "Bearer " + token); interceptor.interceptCall(call, headers, next); @@ -73,6 +78,46 @@ void rejectsMalformedJwtClaims() { assertThat(SessionContext.getScopedRolesMap()).isEmpty(); } + @ParameterizedTest + @MethodSource("invalidSignedAccountIdentities") + void rejectsInvalidSignedAccountIdentityBeforeDispatch(String subject, Object accountId) { + AuthTokenInterceptor interceptor = new AuthTokenInterceptor(jwtUtil); + @SuppressWarnings("unchecked") + ServerCall call = Mockito.mock(ServerCall.class); + @SuppressWarnings("unchecked") + ServerCallHandler next = Mockito.mock(ServerCallHandler.class); + Mockito.when(call.getMethodDescriptor()).thenReturn(METHOD); + Metadata headers = new Metadata(); + headers.put( + AUTH_HEADER, + "Bearer " + + jwtUtil.generateToken( + subject, + Map.of( + "accountId", accountId, + "globalRoles", List.of("platformAdmin"), + "scopedRoles", Map.of()))); + + interceptor.interceptCall(call, headers, next); + + ArgumentCaptor statusCaptor = ArgumentCaptor.forClass(Status.class); + Mockito.verify(call).close(statusCaptor.capture(), Mockito.any(Metadata.class)); + assertThat(statusCaptor.getValue().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + Mockito.verify(next, Mockito.never()).startCall(Mockito.any(), Mockito.any()); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + } + + private static Stream invalidSignedAccountIdentities() { + return Stream.of( + Arguments.of(ACCOUNT_ID, 42L), + Arguments.of(ACCOUNT_ID, List.of(ACCOUNT_ID)), + Arguments.of(ACCOUNT_ID, " " + ACCOUNT_ID), + Arguments.of(ACCOUNT_ID, "00000000-0000-0000-0000-000000000000"), + Arguments.of(ACCOUNT_ID, ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT)), + Arguments.of("018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", ACCOUNT_ID), + Arguments.of("service:game-logic-service", ACCOUNT_ID)); + } + @Test void clearsStaleThreadLocalContextBeforeUnauthenticatedMethodHandler() { AuthTokenInterceptor interceptor = @@ -266,9 +311,9 @@ public void onHalfClose() { Metadata headers = new Metadata(); String token = jwtUtil.generateToken( - "trusted-account", + ACCOUNT_ID, Map.of( - "accountId", "42", + "accountId", ACCOUNT_ID, "globalRoles", List.of(), "scopedRoles", Map.of())); headers.put(AUTH_HEADER, "Bearer " + token); @@ -287,12 +332,12 @@ public void onHalfClose() { exemptInterceptor.interceptCall( authenticatedCall, authenticatedHeaders, receiver))); - assertThat(accountObservedAtStart).hasValue("42"); + assertThat(accountObservedAtStart).hasValue(ACCOUNT_ID); assertThat(callerContextObservedAtStart).isTrue(); assertThat(peerObservedAtStart).hasValue(peerContextValue); listener.onHalfClose(); - assertThat(accountObservedInCallback).hasValue("42"); + assertThat(accountObservedInCallback).hasValue(ACCOUNT_ID); assertThat(callerContextObservedInCallback).isTrue(); assertThat(peerObservedInCallback).hasValue(peerContextValue); assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); @@ -379,9 +424,9 @@ void clearingStaleThreadLocalContextPreservesAnExistingGrpcJwtContext() { Metadata headers = new Metadata(); String token = jwtUtil.generateToken( - "account", + ACCOUNT_ID, Map.of( - "accountId", "42", + "accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"), "scopedRoles", Map.of())); headers.put(AUTH_HEADER, "Bearer " + token); @@ -389,7 +434,7 @@ void clearingStaleThreadLocalContextPreservesAnExistingGrpcJwtContext() { jwtInterceptor.interceptCall(call, headers, next); - assertThat(accountIdSeenByHandler.get()).isEqualTo("42"); + assertThat(accountIdSeenByHandler.get()).isEqualTo(ACCOUNT_ID); assertThat(rolesSeenByHandler.get()).containsExactly("platformAdmin"); assertThat(SessionContext.getAccountId()).isNull(); } @@ -423,8 +468,6 @@ public void onComplete() { jwtUtil.generateToken( "service:game-logic-service", Map.of( - "accountId", - "", "globalRoles", java.util.List.of(), "scopedRoles", @@ -549,8 +592,6 @@ private Metadata internalServiceHeaders() { jwtUtil.generateToken( "service:game-logic-service", Map.of( - "accountId", - "", "globalRoles", java.util.List.of(), "scopedRoles", diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/HttpJwtAuthInterceptorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/HttpJwtAuthInterceptorTest.java index 72c80b55a2..ed33d85d25 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/HttpJwtAuthInterceptorTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/HttpJwtAuthInterceptorTest.java @@ -2,10 +2,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import net.firedevops.firemud.common.security.HttpAuthProperties; import net.firedevops.firemud.common.security.HttpAuthRoleRequirement; import net.firedevops.firemud.common.security.HttpJwtAuthInterceptor; @@ -13,12 +15,16 @@ import net.firedevops.firemud.common.security.SessionContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; class HttpJwtAuthInterceptorTest { + private static final String ACCOUNT_ID = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; private final JwtUtil jwtUtil = new JwtUtil("testsecretkeytestsecretkeytest1234", 3600000L); @AfterEach @@ -78,8 +84,8 @@ void populatesSessionForAuthenticatedRequest() throws Exception { new HttpJwtAuthInterceptor(jwtUtil, authenticatedProperties()); String token = jwtUtil.generateToken( - "user", - Map.of("accountId", "user", "scopedRoles", Map.of("7", List.of("tenantAdmin")))); + ACCOUNT_ID, + Map.of("accountId", ACCOUNT_ID, "scopedRoles", Map.of("7", List.of("tenantAdmin")))); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -87,17 +93,47 @@ void populatesSessionForAuthenticatedRequest() throws Exception { boolean result = interceptor.preHandle(request, response, new Object()); assertTrue(result); - assertEquals("user", SessionContext.getAccountId()); + assertEquals(ACCOUNT_ID, SessionContext.getAccountId()); assertEquals(List.of("tenantAdmin"), SessionContext.getScopedRoles("7")); interceptor.afterCompletion(request, response, new Object(), null); assertTrue(SessionContext.getGlobalRoles().isEmpty()); } + @ParameterizedTest + @MethodSource("invalidSignedAccountIdentities") + void rejectsInvalidSignedAccountIdentityBeforeRoleAuthorization(String subject, Object accountId) + throws Exception { + HttpJwtAuthInterceptor interceptor = + new HttpJwtAuthInterceptor(jwtUtil, privilegedProperties()); + String token = + jwtUtil.generateToken( + subject, Map.of("accountId", accountId, "globalRoles", List.of("platformAdmin"))); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token); + MockHttpServletResponse response = new MockHttpServletResponse(); + + assertFalse(interceptor.preHandle(request, response, new Object())); + assertEquals(HttpStatus.UNAUTHORIZED.value(), response.getStatus()); + assertFalse(SessionContext.hasAuthenticatedCallerContext()); + assertNull(SessionContext.getAccountId()); + } + + private static Stream invalidSignedAccountIdentities() { + return Stream.of( + Arguments.of(ACCOUNT_ID, 42L), + Arguments.of(ACCOUNT_ID, List.of(ACCOUNT_ID)), + Arguments.of(ACCOUNT_ID, " " + ACCOUNT_ID), + Arguments.of(ACCOUNT_ID, "00000000-0000-0000-0000-000000000000"), + Arguments.of(ACCOUNT_ID, ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT)), + Arguments.of("018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", ACCOUNT_ID), + Arguments.of("service:game-session-service", ACCOUNT_ID)); + } + @Test void privilegedModeRejectsNonPrivilegedCaller() throws Exception { HttpJwtAuthInterceptor interceptor = new HttpJwtAuthInterceptor(jwtUtil, privilegedProperties()); - String token = jwtUtil.generateToken("user", Map.of("accountId", "user")); + String token = jwtUtil.generateToken(ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID)); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -130,6 +166,7 @@ void populatesSharedInternalServiceIdentity() throws Exception { assertTrue(result); assertTrue(SessionContext.isInternalService()); + assertEquals("", SessionContext.getAccountId()); assertEquals("game-session-service", SessionContext.getServiceName()); assertEquals("game-session-service-1", SessionContext.getServiceInstanceId()); } @@ -140,10 +177,10 @@ void rejectsMalformedGlobalRolesClaimShape() throws Exception { new HttpJwtAuthInterceptor(jwtUtil, authenticatedProperties()); String token = jwtUtil.generateToken( - "user", + ACCOUNT_ID, Map.of( "accountId", - "user", + ACCOUNT_ID, "globalRoles", "platformAdmin", "scopedRoles", diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtClaimsTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtClaimsTest.java index 97c999e90d..7b81647534 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtClaimsTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtClaimsTest.java @@ -11,10 +11,12 @@ import org.junit.jupiter.api.Test; class JwtClaimsTest { + private static final String ACCOUNT_UUID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + @Test void requireLongParsesNumericTextAndRejectsInvalidValues() { - assertEquals(7L, JwtClaims.requireLong("7", "accountId", false)); - assertEquals(7L, JwtClaims.requireLong(7L, "accountId", false)); + assertEquals(7L, JwtClaims.requireLong("7", "tenantId", false)); + assertEquals(7L, JwtClaims.requireLong(7L, "tenantId", false)); assertThrows( IllegalArgumentException.class, () -> JwtClaims.requireLong("abc", "tenantId", false)); @@ -42,40 +44,47 @@ void requireClaimRejectsMissingOrBlankClaimsAndReadsFirstIterableValue() { } @Test - void requireSignedActorAccountIdRejectsMalformedOrMismatchedAccountClaims() { + void requireSignedGameplayAccountUuidRejectsMalformedOrMismatchedAccountClaims() { JwtUtil jwtUtil = new JwtUtil("mysecretkey123456789012345678901", 30_000L); Claims validClaims = - jwtUtil.parseToken(jwtUtil.generateToken("11", Map.of("accountId", "11"))).getPayload(); + jwtUtil + .parseToken(jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID))) + .getPayload(); assertEquals( - 11L, JwtClaims.requireSignedActorAccountId(validClaims, "signed token account mismatch")); + ACCOUNT_UUID, + JwtClaims.requireSignedGameplayAccountUuid(validClaims, "signed token account mismatch")); Claims malformedSubjectClaims = jwtUtil - .parseToken(jwtUtil.generateToken("not-a-number", Map.of("accountId", "11"))) + .parseToken(jwtUtil.generateToken("not-a-uuid", Map.of("accountId", ACCOUNT_UUID))) .getPayload(); assertThrows( IllegalArgumentException.class, () -> - JwtClaims.requireSignedActorAccountId( + JwtClaims.requireSignedGameplayAccountUuid( malformedSubjectClaims, "signed token account mismatch")); Claims malformedAccountClaims = jwtUtil - .parseToken(jwtUtil.generateToken("11", Map.of("accountId", "not-a-number"))) + .parseToken(jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", "not-a-uuid"))) .getPayload(); assertThrows( IllegalArgumentException.class, () -> - JwtClaims.requireSignedActorAccountId( + JwtClaims.requireSignedGameplayAccountUuid( malformedAccountClaims, "signed token account mismatch")); Claims mismatchedClaims = - jwtUtil.parseToken(jwtUtil.generateToken("11", Map.of("accountId", "12"))).getPayload(); + jwtUtil + .parseToken( + jwtUtil.generateToken( + ACCOUNT_UUID, Map.of("accountId", "4d3e9d15-a02e-41db-8648-0d2c68d0f0a3"))) + .getPayload(); IllegalArgumentException mismatch = assertThrows( IllegalArgumentException.class, - () -> JwtClaims.requireSignedActorAccountId(mismatchedClaims, "custom mismatch")); + () -> JwtClaims.requireSignedGameplayAccountUuid(mismatchedClaims, "custom mismatch")); assertEquals("custom mismatch", mismatch.getMessage()); } @@ -87,10 +96,10 @@ void requireSignedGameplayRoutingClaimsRejectsMalformedOrIncompleteRoutingBundle jwtUtil .parseToken( jwtUtil.generateToken( - "11", + ACCOUNT_UUID, Map.of( "accountId", - "11", + ACCOUNT_UUID, "tenantId", "7", "worldSlug", @@ -104,7 +113,7 @@ void requireSignedGameplayRoutingClaimsRejectsMalformedOrIncompleteRoutingBundle .getPayload(); JwtClaims.SignedGameplayRoutingClaims routingClaims = JwtClaims.requireSignedGameplayRoutingClaims(validClaims, "signed gameplay mismatch"); - assertEquals(11L, routingClaims.accountId()); + assertEquals(ACCOUNT_UUID, routingClaims.accountId()); assertEquals(7L, routingClaims.tenantId()); assertEquals("demo", routingClaims.worldSlug()); assertEquals("production", routingClaims.realmSlug()); @@ -115,10 +124,10 @@ void requireSignedGameplayRoutingClaimsRejectsMalformedOrIncompleteRoutingBundle jwtUtil .parseToken( jwtUtil.generateToken( - "11", + ACCOUNT_UUID, Map.of( "accountId", - "11", + ACCOUNT_UUID, "tenantId", "7", "worldSlug", @@ -140,10 +149,10 @@ void requireSignedGameplayRoutingClaimsRejectsMalformedOrIncompleteRoutingBundle jwtUtil .parseToken( jwtUtil.generateToken( - "11", + ACCOUNT_UUID, Map.of( "accountId", - "11", + ACCOUNT_UUID, "tenantId", "7", "worldSlug", @@ -161,4 +170,45 @@ void requireSignedGameplayRoutingClaimsRejectsMalformedOrIncompleteRoutingBundle JwtClaims.requireSignedGameplayRoutingClaims( zeroPointerClaims, "signed gameplay mismatch")); } + + @Test + void requireSignedGameplayAccountUuidRejectsNoncanonicalOrIncompatibleCarriers() { + JwtUtil jwtUtil = new JwtUtil("mysecretkey123456789012345678901", 30_000L); + + for (String accountId : + List.of( + "11", + "not-a-uuid", + "4CAE05E8-7A6B-4B14-9D44-665E3EEC450B", + "00000000-0000-0000-0000-000000000000", + " " + ACCOUNT_UUID)) { + Claims claims = + jwtUtil + .parseToken(jwtUtil.generateToken(accountId, Map.of("accountId", accountId))) + .getPayload(); + assertThrows( + IllegalArgumentException.class, + () -> JwtClaims.requireSignedGameplayAccountUuid(claims, "account subject mismatch")); + } + + Claims mismatchedClaims = + jwtUtil + .parseToken( + jwtUtil.generateToken( + ACCOUNT_UUID, Map.of("accountId", "4d3e9d15-a02e-41db-8648-0d2c68d0f0a3"))) + .getPayload(); + assertThrows( + IllegalArgumentException.class, + () -> + JwtClaims.requireSignedGameplayAccountUuid( + mismatchedClaims, "account subject mismatch")); + + Claims numericClaim = + jwtUtil + .parseToken(jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", 42L))) + .getPayload(); + assertThrows( + IllegalArgumentException.class, + () -> JwtClaims.requireSignedGameplayAccountUuid(numericClaim, "account subject mismatch")); + } } diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java index abc3e59a76..e64a9abbc3 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java @@ -4,15 +4,57 @@ import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.GetProfileRequest; +import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.UpdateProfileRequest; import net.firedevops.firemud.common.account.AccountProfileJson; import org.junit.jupiter.api.Test; class AccountRuntimeStubServerTest { + @Test + void runtimeEvidenceUsesTheExplicitTestClockInsteadOfAnExpiredCalendarFixture() throws Exception { + var now = Instant.parse("2026-10-30T00:00:00Z"); + try (var server = new AccountRuntimeStubServer(0, Clock.fixed(now, ZoneOffset.UTC))) { + var channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + String account = AccountRuntimeStubServer.accountUuidForTestFixture(7L); + var membership = + stub.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(account) + .setTenantId("1") + .build()); + var grant = + stub.getRealmAccessGrantForRuntime( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId(account) + .setTenantId("1") + .setWorldSlug("world") + .setRealmSlug("realm") + .build()); + var entitlement = + stub.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder().setTenantId("1").build()); + assertThat(membership.getEvaluatedAt()).isEqualTo(now.toString()); + assertThat(grant.getEvaluatedAt()).isEqualTo(now.toString()); + assertThat(entitlement.getEvaluatedAt()).isEqualTo(now.toString()); + assertThat(membership.getAccountId()).isEqualTo(account); + assertThat(grant.getAccountId()).isEqualTo(account); + } finally { + channel.shutdownNow(); + } + } + } + @Test void authenticationCanonicalizesMappedEmailAndMissingMembershipDeniesAdmission() throws Exception { @@ -31,7 +73,7 @@ void authenticationCanonicalizesMappedEmailAndMissingMembershipDeniesAdmission() .setPassword("password") .build()) .getAccountId()) - .isEqualTo("7"); + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(7L)); server.setMembershipExists(false); @@ -58,11 +100,16 @@ void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { try { AccountServiceGrpc.AccountServiceBlockingStub stub = AccountServiceGrpc.newBlockingStub(channel); + server.mapAccountId("demo@example.com", 7L); + String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); AccountProfileJson initialProfile = AccountProfileJson.parse( stub.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("7").build()) + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(accountUuid) + .build()) .getProfileJson(), "FRIENDS_ONLY"); assertThat(initialProfile.presenceVisibilityPolicy()).isEqualTo("FRIENDS_ONLY"); @@ -71,7 +118,7 @@ void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { stub.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("1") - .setAccountId("7") + .setAccountId(accountUuid) .setProfileJson( """ {"displayName":"Demo-7","bio":null,"presenceVisibilityPolicy":"PRIVATE"} @@ -83,7 +130,10 @@ void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { AccountProfileJson updatedProfile = AccountProfileJson.parse( stub.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("7").build()) + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(accountUuid) + .build()) .getProfileJson(), "FRIENDS_ONLY"); assertThat(updatedProfile.presenceVisibilityPolicy()).isEqualTo("PRIVATE"); @@ -101,12 +151,14 @@ void resetRuntimeStateRestoresDefaultVisibilityPolicy() throws Exception { try { AccountServiceGrpc.AccountServiceBlockingStub stub = AccountServiceGrpc.newBlockingStub(channel); + server.setDefaultAccountId(7L); + String accountUuid = authenticate(stub); assertThat( stub.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("1") - .setAccountId("7") + .setAccountId(accountUuid) .setProfileJson( """ {"displayName":"Demo-7","bio":null,"presenceVisibilityPolicy":"PRIVATE"} @@ -116,11 +168,21 @@ void resetRuntimeStateRestoresDefaultVisibilityPolicy() throws Exception { .isTrue(); server.resetRuntimeState(); + var deniedAfterReset = + stub.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(accountUuid).build()); + assertThat(deniedAfterReset.getProfileJson()).isEmpty(); + assertThat(deniedAfterReset.getError().getCode()).isEqualTo("ACCOUNT_NOT_FOUND"); + + accountUuid = authenticate(stub); AccountProfileJson resetProfile = AccountProfileJson.parse( stub.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("7").build()) + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(accountUuid) + .build()) .getProfileJson(), "FRIENDS_ONLY"); assertThat(resetProfile.presenceVisibilityPolicy()).isEqualTo("FRIENDS_ONLY"); @@ -129,4 +191,57 @@ void resetRuntimeStateRestoresDefaultVisibilityPolicy() throws Exception { } } } + + @Test + void profileReadAndWriteRejectUnknownAndMalformedAccountUuids() throws Exception { + try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + AccountServiceGrpc.AccountServiceBlockingStub stub = + AccountServiceGrpc.newBlockingStub(channel); + String unregisteredUuid = AccountRuntimeStubServer.accountUuidForTestFixture(9L); + + for (String accountId : new String[] {unregisteredUuid, "9", "not-a-uuid"}) { + var read = + stub.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(accountId).build()); + assertThat(read.getProfileJson()).isEmpty(); + assertThat(read.getError().getCode()).isEqualTo("ACCOUNT_NOT_FOUND"); + + var write = + stub.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(accountId) + .setProfileJson( + "{\"displayName\":\"Changed\",\"bio\":null,\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build()); + assertThat(write.getSuccess()).isFalse(); + assertThat(write.getError().getCode()).isEqualTo("ACCOUNT_NOT_FOUND"); + } + + server.setDefaultAccountId(9L); + String authenticatedUuid = authenticate(stub); + AccountProfileJson profile = + AccountProfileJson.parse( + stub.getProfile( + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(authenticatedUuid) + .build()) + .getProfileJson(), + "FRIENDS_ONLY"); + assertThat(profile.displayName()).isEqualTo("Demo-9"); + assertThat(profile.presenceVisibilityPolicy()).isEqualTo("FRIENDS_ONLY"); + } finally { + channel.shutdownNow(); + } + } + } + + private static String authenticate(AccountServiceGrpc.AccountServiceBlockingStub stub) { + return stub.authenticate(AuthenticateRequest.newBuilder().setEmail("demo@example.com").build()) + .getAccountId(); + } } diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index 4bb8d1f7a5..060d331a7b 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -4,9 +4,12 @@ import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.stub.StreamObserver; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Clock; import java.time.Instant; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -40,7 +43,6 @@ /** Shared fake Account runtime authority for cross-service gameplay tests. */ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountServiceImplBase implements AutoCloseable { - private static final String EVALUATED_AT = "2026-03-30T00:00:00Z"; private static final Set IMPLEMENTED_RUNTIME_METHODS = Set.of( "Ping", @@ -52,6 +54,7 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe "JoinPublicProductionMembership"); private final Server server; + private final Clock clock; private final List authenticateRequests = new CopyOnWriteArrayList<>(); private final AtomicBoolean membershipExists = new AtomicBoolean(true); private final AtomicBoolean gameplayAdmissionAllowed = new AtomicBoolean(true); @@ -61,10 +64,17 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe private final AtomicLong defaultAccountId = new AtomicLong(1L); private final AtomicLong nextConnectScopeId = new AtomicLong(1L); private final Map accountIdsByEmail = new ConcurrentHashMap<>(); + private final Map accountIdsByUuid = new ConcurrentHashMap<>(); private final Map profilesByAccountId = new ConcurrentHashMap<>(); private final Map connectScopesById = new ConcurrentHashMap<>(); public AccountRuntimeStubServer(int port) throws IOException { + this(port, Clock.systemUTC()); + } + + /** Test-owned time for fresh runtime evidence and its original connect-scope expiry. */ + public AccountRuntimeStubServer(int port, Clock clock) throws IOException { + this.clock = Objects.requireNonNull(clock, "clock"); this.server = NettyServerBuilder.forPort(port).addService(this).build().start(); } @@ -84,8 +94,19 @@ public void setDefaultAccountId(long accountId) { defaultAccountId.set(accountId); } + /** Returns the stable UUID used by this fake for a numeric test account key. */ + public static String accountUuidForTestFixture(long accountId) { + if (accountId <= 0L) { + throw new IllegalArgumentException("accountId must be positive"); + } + return UUID.nameUUIDFromBytes( + ("firemud-test-account:" + accountId).getBytes(StandardCharsets.UTF_8)) + .toString(); + } + public void mapAccountId(String email, long accountId) { accountIdsByEmail.put(EmailCanonicalization.normalize(email), accountId); + accountIdsByUuid.put(accountUuidForTestFixture(accountId), accountId); } public void setPresenceVisibilityPolicy(long accountId, String visibilityPolicy) { @@ -137,6 +158,7 @@ public void resetRuntimeState() { allowPublicJoin.set(true); realmAccessGranted.set(true); profilesByAccountId.clear(); + accountIdsByUuid.clear(); connectScopesById.clear(); } @@ -153,9 +175,11 @@ public void authenticate( String canonicalEmail = EmailCanonicalization.normalize(request.getEmail()); long accountId = accountIdsByEmail.getOrDefault(canonicalEmail, defaultAccountId.get()); profilesByAccountId.computeIfAbsent(accountId, StubProfile::defaultFor); + String accountUuid = accountUuidForTestFixture(accountId); + accountIdsByUuid.put(accountUuid, accountId); responseObserver.onNext( AuthenticateResponse.newBuilder() - .setAccountId(Long.toString(accountId)) + .setAccountId(accountUuid) .setAuthToken("stub-token-" + accountId) .build()); responseObserver.onCompleted(); @@ -175,7 +199,7 @@ public void getTenantMembershipForRuntime( .setMembershipVersion(exists ? 1L : 0L) .setMembershipLifecycleState(exists ? "ACTIVE" : "MISSING") .setMembershipAuthorityGeneration(exists ? 1L : 0L) - .setEvaluatedAt(EVALUATED_AT) + .setEvaluatedAt(clock.instant().toString()) .build()); responseObserver.onCompleted(); } @@ -192,7 +216,7 @@ public void getRealmAccessGrantForRuntime( .setRealmSlug(request.getRealmSlug()) .setGranted(realmAccessGranted.get()) .setGrantVersion(1L) - .setEvaluatedAt(EVALUATED_AT) + .setEvaluatedAt(clock.instant().toString()) .build()); responseObserver.onCompleted(); } @@ -208,7 +232,7 @@ public void getTenantEntitlementsForRuntime( .setAllowPublicJoin(allowPublicJoin.get()) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt(EVALUATED_AT) + .setEvaluatedAt(clock.instant().toString()) .build()); responseObserver.onCompleted(); } @@ -252,7 +276,7 @@ public void issueDirectTextConnectScope( .build()); } else { String scopeId = "stub-connect-scope-" + nextConnectScopeId.getAndIncrement(); - Instant expiresAt = Instant.now().plusSeconds(300); + Instant expiresAt = clock.instant().plusSeconds(300); connectScopesById.put( scopeId, new StubConnectScope( @@ -296,7 +320,7 @@ public void joinPublicProductionMembership( || caller.getTenantId().isBlank() || caller.getSessionId().isBlank() || scope == null - || !scope.expiresAt().isAfter(Instant.now()) + || !scope.expiresAt().isAfter(clock.instant()) || !scope.accountId().equals(caller.getAccountId()) || !scope.tenantId().equals(caller.getTenantId()) || !scope.realmId().equals(caller.getRealmId()) @@ -338,7 +362,15 @@ public void joinPublicProductionMembership( @Override public void getProfile( GetProfileRequest request, StreamObserver responseObserver) { - long accountId = Long.parseLong(request.getAccountId()); + Long accountId = resolveRegisteredAccountId(request.getAccountId()); + if (accountId == null) { + responseObserver.onNext( + GetProfileResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("ACCOUNT_NOT_FOUND")) + .build()); + responseObserver.onCompleted(); + return; + } StubProfile profile = profilesByAccountId.computeIfAbsent(accountId, StubProfile::defaultFor); try { responseObserver.onNext( @@ -359,7 +391,15 @@ public void getProfile( public void updateProfile( UpdateProfileRequest request, StreamObserver responseObserver) { try { - long accountId = Long.parseLong(request.getAccountId()); + Long accountId = resolveRegisteredAccountId(request.getAccountId()); + if (accountId == null) { + responseObserver.onNext( + UpdateProfileResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("ACCOUNT_NOT_FOUND")) + .build()); + responseObserver.onCompleted(); + return; + } AccountProfileJson profile = AccountProfileJson.parse(request.getProfileJson(), StubProfile.DEFAULT_VISIBILITY_POLICY); StubProfile existing = @@ -380,6 +420,18 @@ public void updateProfile( } } + private Long resolveRegisteredAccountId(String accountUuid) { + try { + UUID parsed = UUID.fromString(accountUuid); + if (parsed.equals(new UUID(0L, 0L)) || !parsed.toString().equals(accountUuid)) { + return null; + } + return accountIdsByUuid.get(accountUuid); + } catch (IllegalArgumentException ex) { + return null; + } + } + @Override public void close() { server.shutdownNow(); diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java index 926dee9c20..252a22c196 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java @@ -6,6 +6,7 @@ import java.util.List; import java.util.Optional; import java.util.TreeSet; +import java.util.UUID; import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.common.grpc.GrpcAppErrors; @@ -40,6 +41,7 @@ public class CommunicationAggregationService { private static final Logger LOG = LoggerFactory.getLogger(CommunicationAggregationService.class); private static final String OBSERVER_METADATA_ONLY_FLAG = "observer_metadata_only"; + private static final UUID NIL_ACCOUNT_UUID = new UUID(0L, 0L); private final SocialGroupsServiceGrpc.SocialGroupsServiceBlockingStub socialStub; private final EntityManagementServiceGrpc.EntityManagementServiceBlockingStub entityStub; @@ -56,10 +58,10 @@ public SendCommunicationResponse send(SendCommunicationRequest request) { SendCommunicationResponse.newBuilder() .setType(request.getType()) .setMessage(normalizedText); - String validatedAccountId = parsePositiveAccountId(request.getAccountId()); - if (validatedAccountId == null) { + String validatedAccountUuid = parseCanonicalAccountUuid(request.getAccountId()); + if (validatedAccountUuid == null) { return errorResponse( - builder, "INVALID_ARGUMENT", "account_id must be a positive numeric account id"); + builder, "INVALID_ARGUMENT", "account_id must be a canonical non-nil Account UUID"); } if (tenantId != null && !isSocialCapabilityEnabled(tenantId, gameInstanceId)) { @@ -102,7 +104,7 @@ public SendCommunicationResponse send(SendCommunicationRequest request) { socialStub.sendMessage( SendMessageRequest.newBuilder() .setTenantId(request.getTenantId()) - .setSenderId(validatedAccountId) + .setSenderId(validatedAccountUuid) .setType(mapType(request.getType())) .setContent(normalizedText) .setRecipientId(audience.recipientId().orElse("")) @@ -396,15 +398,16 @@ private Long parseTenantId(String tenantId) { } } - private String parsePositiveAccountId(String accountId) { - if (!StringUtils.hasText(accountId)) { + private String parseCanonicalAccountUuid(String accountUuid) { + if (accountUuid == null || accountUuid.isEmpty()) { return null; } - String normalized = accountId.trim(); try { - long parsed = Long.parseLong(normalized); - return parsed > 0L ? Long.toString(parsed) : null; - } catch (NumberFormatException ignored) { + UUID parsed = UUID.fromString(accountUuid); + return parsed.equals(NIL_ACCOUNT_UUID) || !parsed.toString().equals(accountUuid) + ? null + : accountUuid; + } catch (IllegalArgumentException ignored) { return null; } } diff --git a/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java b/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java index 5091a32be2..b13a3656b4 100644 --- a/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java +++ b/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java @@ -41,7 +41,7 @@ @ExtendWith(MockitoExtension.class) class CommunicationAggregationServiceTest { - private static final String VALID_ACCOUNT_ID = "42"; + private static final String VALID_ACCOUNT_ID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; @Mock private SocialGroupsServiceGrpc.SocialGroupsServiceBlockingStub socialStub; @@ -125,14 +125,16 @@ void unavailableSocialCapabilityAuthorityFailsClosedWithoutCallingDownstreamServ } @Test - void rejectsMissingMalformedAndNonPositiveAccountIdsBeforeDownstreamCalls() { + void rejectsMissingMalformedAndNonCanonicalAccountUuidsBeforeDownstreamCalls() { for (String[] accountIdCase : new String[][] { {"empty", ""}, {"whitespace-only", " "}, - {"malformed", "not-a-number"}, - {"zero", "0"}, - {"negative", "-1"}, + {"malformed", "not-a-uuid"}, + {"numeric", "42"}, + {"nil", "00000000-0000-0000-0000-000000000000"}, + {"uppercase", VALID_ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT)}, + {"whitespace-padded", " " + VALID_ACCOUNT_ID + " "}, }) { String accountIdCaseDescription = accountIdCase[0]; String accountId = accountIdCase[1]; @@ -154,7 +156,7 @@ void rejectsMissingMalformedAndNonPositiveAccountIdsBeforeDownstreamCalls() { .isEqualTo("INVALID_ARGUMENT"); assertThat(resp.getError().getMessage()) .as(accountIdCaseDescription) - .isEqualTo("account_id must be a positive numeric account id"); + .isEqualTo("account_id must be a canonical non-nil Account UUID"); } verify(entityStub, never()).listRoomEntities(any()); @@ -162,27 +164,26 @@ void rejectsMissingMalformedAndNonPositiveAccountIdsBeforeDownstreamCalls() { } @Test - void normalizesPaddedNoncanonicalAccountIdForSocialSender() { - when(socialStub.sendMessage(any())) - .thenReturn(SendMessageResponse.newBuilder().setSuccess(true).build()); - + void rejectsWhitespacePaddedAccountUuidBeforeDownstreamCalls() { SendCommunicationResponse resp = service.send( SendCommunicationRequest.newBuilder() .setTenantId("tenant-1") .setSessionId("sess-1") .setCharacterId("player-0") - .setAccountId(" 0042 ") + .setAccountId(" " + VALID_ACCOUNT_ID + " ") .setType(CommunicationType.TELL) .setTargetCharacterId("player-9") .setTargetCharacterName("Sora") .setText("Meet me outside") .build()); - assertThat(resp.getSuccess()).isTrue(); - ArgumentCaptor captor = ArgumentCaptor.forClass(SendMessageRequest.class); - verify(socialStub).sendMessage(captor.capture()); - assertThat(captor.getValue().getSenderId()).isEqualTo("42"); + assertThat(resp.getSuccess()).isFalse(); + assertThat(resp.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(resp.getError().getMessage()) + .isEqualTo("account_id must be a canonical non-nil Account UUID"); + verify(entityStub, never()).listRoomEntities(any()); + verify(socialStub, never()).sendMessage(any()); } @Test diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java index bd417a98ea..65b35dcb8e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java @@ -24,6 +24,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.shared.v1.ErrorDetail; import org.slf4j.Logger; import org.springframework.stereotype.Component; @@ -164,6 +165,11 @@ public GetTenantMembershipForRuntimeResponse getTenantMembershipForRuntime( if (stub() == null) { return membershipAuthorityUnavailable(); } + try { + JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); + } catch (IllegalArgumentException ex) { + return membershipAuthorityUnavailable(); + } GetTenantMembershipForRuntimeRequest request = GetTenantMembershipForRuntimeRequest.newBuilder() .setAccountId(accountId) @@ -171,14 +177,14 @@ public GetTenantMembershipForRuntimeResponse getTenantMembershipForRuntime( .setRequestId(requestId == null ? "" : requestId) .build(); try { - return callStub().getTenantMembershipForRuntime(request); + return correlateMembership(callStub().getTenantMembershipForRuntime(request), request); } catch (StatusRuntimeException ex) { if (ex.getStatus().getCode() == Status.Code.UNAVAILABLE) { logger.warn( "Account Service unavailable; rebuilding channel and retrying runtime membership", ex); try { initClient(); - return callStub().getTenantMembershipForRuntime(request); + return correlateMembership(callStub().getTenantMembershipForRuntime(request), request); } catch (Exception retryEx) { logger.warn( "Failed to retry Account Service runtime membership after channel reload", retryEx); @@ -239,6 +245,11 @@ public GetRealmAccessGrantForRuntimeResponse getRealmAccessGrantForRuntime( if (stub() == null) { return realmAccessGrantUnavailable(); } + try { + JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); + } catch (IllegalArgumentException ex) { + return realmAccessGrantUnavailable(); + } GetRealmAccessGrantForRuntimeRequest request = GetRealmAccessGrantForRuntimeRequest.newBuilder() .setAccountId(accountId) @@ -248,7 +259,7 @@ public GetRealmAccessGrantForRuntimeResponse getRealmAccessGrantForRuntime( .setRequestId(requestId == null ? "" : requestId) .build(); try { - return callStub().getRealmAccessGrantForRuntime(request); + return correlateRealmGrant(callStub().getRealmAccessGrantForRuntime(request), request); } catch (StatusRuntimeException ex) { if (ex.getStatus().getCode() == Status.Code.UNAVAILABLE) { logger.warn( @@ -256,7 +267,7 @@ public GetRealmAccessGrantForRuntimeResponse getRealmAccessGrantForRuntime( ex); try { initClient(); - return callStub().getRealmAccessGrantForRuntime(request); + return correlateRealmGrant(callStub().getRealmAccessGrantForRuntime(request), request); } catch (Exception retryEx) { logger.warn( "Failed to retry Account Service realm access grant read after channel reload", @@ -271,6 +282,36 @@ public GetRealmAccessGrantForRuntimeResponse getRealmAccessGrantForRuntime( return realmAccessGrantUnavailable(); } + private GetTenantMembershipForRuntimeResponse correlateMembership( + GetTenantMembershipForRuntimeResponse response, + GetTenantMembershipForRuntimeRequest request) { + if (response != null && response.hasError()) { + return response; + } + if (response == null + || !request.getAccountId().equals(response.getAccountId()) + || !request.getTenantId().equals(response.getTenantId())) { + return membershipAuthorityUnavailable(); + } + return response; + } + + private GetRealmAccessGrantForRuntimeResponse correlateRealmGrant( + GetRealmAccessGrantForRuntimeResponse response, + GetRealmAccessGrantForRuntimeRequest request) { + if (response != null && response.hasError()) { + return response; + } + if (response == null + || !request.getAccountId().equals(response.getAccountId()) + || !request.getTenantId().equals(response.getTenantId()) + || !request.getWorldSlug().equals(response.getWorldSlug()) + || !request.getRealmSlug().equals(response.getRealmSlug())) { + return realmAccessGrantUnavailable(); + } + return response; + } + private GetRealmAccessGrantForRuntimeResponse realmAccessGrantUnavailable() { return GetRealmAccessGrantForRuntimeResponse.newBuilder() .setError( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java index 820bcad714..1f9c2b0d08 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java @@ -12,6 +12,7 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.security.GameplaySessionAttestationService; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.entitymanagement.v1.Character; import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; import net.firedevops.firemud.entitymanagement.v1.FindCharacterByNameRequest; @@ -139,7 +140,7 @@ public ListCharactersByAccountResponse listCharactersByAccount( ListCharactersByAccountRequest request = ListCharactersByAccountRequest.newBuilder() .setTenantId(tenantId) - .setAccountId(accountId) + .setAccountId(JwtClaims.requireCanonicalAccountUuid(accountId, "accountId")) .setGameInstanceId(gameInstanceId) .setPlayableStateScope(playableStateScope) .build(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java index a2720f8f0f..f30d4658df 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java @@ -9,6 +9,7 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.security.GameplaySessionAttestationService; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.entitymanagement.v1.ApplyActorConditionRequest; import net.firedevops.firemud.entitymanagement.v1.ApplyActorConditionResponse; import net.firedevops.firemud.entitymanagement.v1.DropItemToRoomRequest; @@ -140,18 +141,22 @@ public SendCommunicationResponse sendCommunication( String targetCharacterId, String targetCharacterName, String effectId) { + String accountUuid = context.accountId(); + if (!SessionContext.isCanonicalAccountIdentity(accountUuid)) { + throw new IllegalArgumentException( + "Session context must contain a canonical non-nil Account UUID"); + } String canonicalRoomId = GameplayRuntimeRoomIds.requireCanonical(roomId, "roomInstanceId"); String tenantId = Long.toString(context.tenantId()); String sessionId = Long.toString(context.sessionId()); String characterId = Long.toString(context.characterId()); - String accountId = context.accountId(); String gameInstanceId = Long.toString(context.gameInstanceId()); SendCommunicationRequest request = SendCommunicationRequest.newBuilder() .setTenantId(tenantId) .setSessionId(sessionId) .setCharacterId(characterId) - .setAccountId(accountId == null ? "" : accountId) + .setAccountId(accountUuid) .setRoomInstance( RoomInstanceRef.newBuilder() .setTenantId(tenantId) @@ -330,7 +335,7 @@ public PickupItemFromRoomResponse pickupVisibleRoomItem( SessionContext context, String itemReference, int quantity, String effectId) { String tenantId = Long.toString(context.tenantId()); String sessionId = Long.toString(context.sessionId()); - String accountId = context.accountId(); + String accountId = JwtClaims.requireCanonicalAccountUuid(context.accountId(), "accountId"); String characterId = Long.toString(context.characterId()); String gameInstanceId = Long.toString(context.gameInstanceId()); String roomInstanceId = @@ -339,7 +344,7 @@ public PickupItemFromRoomResponse pickupVisibleRoomItem( PickupVisibleRoomItemRequest.newBuilder() .setTenantId(tenantId) .setSessionId(sessionId) - .setAccountId(accountId == null ? "" : accountId) + .setAccountId(accountId) .setCharacterId(characterId) .setGameInstanceId(gameInstanceId) .setRoomInstanceId(roomInstanceId) @@ -433,7 +438,7 @@ public DropItemToRoomResponse dropCarriedItem( SessionContext context, String itemReference, int quantity, String effectId) { String tenantId = Long.toString(context.tenantId()); String sessionId = Long.toString(context.sessionId()); - String accountId = context.accountId(); + String accountId = JwtClaims.requireCanonicalAccountUuid(context.accountId(), "accountId"); String characterId = Long.toString(context.characterId()); String gameInstanceId = Long.toString(context.gameInstanceId()); String roomInstanceId = @@ -442,7 +447,7 @@ public DropItemToRoomResponse dropCarriedItem( DropCarriedItemRequest.newBuilder() .setTenantId(tenantId) .setSessionId(sessionId) - .setAccountId(accountId == null ? "" : accountId) + .setAccountId(accountId) .setCharacterId(characterId) .setGameInstanceId(gameInstanceId) .setRoomInstanceId(roomInstanceId) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/ModerationPolicyClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/ModerationPolicyClient.java index 3ad6c4b534..6bb424ce5d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/ModerationPolicyClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/ModerationPolicyClient.java @@ -8,6 +8,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.loggingadmin.v1.EvaluateModerationPolicyRequest; import net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse; import net.firedevops.firemud.loggingadmin.v1.LoggingAdminServiceGrpc; @@ -50,11 +51,12 @@ protected LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub buildStub( LoggingAdminServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } - public EvaluateModerationPolicyResponse evaluateGameplayAdmission(long tenantId, long accountId) { + public EvaluateModerationPolicyResponse evaluateGameplayAdmission( + long tenantId, String accountId) { EvaluateModerationPolicyRequest request = EvaluateModerationPolicyRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(JwtClaims.requireCanonicalAccountUuid(accountId, "accountId")) .setScope(SCOPE_GAMEPLAY_ADMISSION) .build(); return stub().evaluateModerationPolicy(request); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialGroupsClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialGroupsClient.java index 050a9b781b..ee44720ec7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialGroupsClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/SocialGroupsClient.java @@ -8,6 +8,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.socialgroups.v1.AddFriendRequest; import net.firedevops.firemud.socialgroups.v1.AddFriendResponse; import net.firedevops.firemud.socialgroups.v1.FriendRosterFilter; @@ -67,107 +68,113 @@ protected SocialGroupsServiceGrpc.SocialGroupsServiceBlockingStub buildStub( SocialGroupsServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } - public ListFriendPresenceResponse listFriendPresence(long tenantId, long accountId) { + public ListFriendPresenceResponse listFriendPresence(long tenantId, String accountId) { return callStub() .listFriendPresence( ListFriendPresenceRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(JwtClaims.requireCanonicalAccountUuid(accountId, "accountId")) .build()); } - public ListFriendsResponse listFriends(long tenantId, long accountId, FriendRosterFilter filter) { + public ListFriendsResponse listFriends( + long tenantId, String accountId, FriendRosterFilter filter) { return callStub() .listFriends( ListFriendsRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(JwtClaims.requireCanonicalAccountUuid(accountId, "accountId")) .setFilter(filter) .build()); } - public ListFriendsResponse listFriends(long tenantId, long accountId) { + public ListFriendsResponse listFriends(long tenantId, String accountId) { return listFriends(tenantId, accountId, FriendRosterFilter.FRIEND_ROSTER_FILTER_ALL); } - public AddFriendResponse addFriend(long tenantId, long accountId, long friendAccountId) { + public AddFriendResponse addFriend(long tenantId, String accountId, String friendAccountId) { return callStub() .addFriend( AddFriendRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setFriendAccountId(Long.toString(friendAccountId)) + .setAccountId(JwtClaims.requireCanonicalAccountUuid(accountId, "accountId")) + .setFriendAccountId( + JwtClaims.requireCanonicalAccountUuid(friendAccountId, "friendAccountId")) .build()); } - public RemoveFriendResponse removeFriend(long tenantId, long accountId, long friendAccountId) { + public RemoveFriendResponse removeFriend( + long tenantId, String accountId, String friendAccountId) { return callStub() .removeFriend( RemoveFriendRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setFriendAccountId(Long.toString(friendAccountId)) + .setAccountId(JwtClaims.requireCanonicalAccountUuid(accountId, "accountId")) + .setFriendAccountId( + JwtClaims.requireCanonicalAccountUuid(friendAccountId, "friendAccountId")) .build()); } public RemoveFriendByOrdinalResponse removeFriendByOrdinal( - long tenantId, long accountId, int ordinal) { + long tenantId, String accountId, int ordinal) { return callStub() .removeFriendByOrdinal( RemoveFriendByOrdinalRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(JwtClaims.requireCanonicalAccountUuid(accountId, "accountId")) .setOrdinal(ordinal) .build()); } - public GetFriendResponse getFriend(long tenantId, long accountId, long friendAccountId) { + public GetFriendResponse getFriend(long tenantId, String accountId, String friendAccountId) { return callStub() .getFriend( GetFriendRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) - .setFriendAccountId(Long.toString(friendAccountId)) + .setAccountId(JwtClaims.requireCanonicalAccountUuid(accountId, "accountId")) + .setFriendAccountId( + JwtClaims.requireCanonicalAccountUuid(friendAccountId, "friendAccountId")) .build()); } - public GetFriendByOrdinalResponse getFriendByOrdinal(long tenantId, long accountId, int ordinal) { + public GetFriendByOrdinalResponse getFriendByOrdinal( + long tenantId, String accountId, int ordinal) { return callStub() .getFriendByOrdinal( GetFriendByOrdinalRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(JwtClaims.requireCanonicalAccountUuid(accountId, "accountId")) .setOrdinal(ordinal) .build()); } - public GetFriendRosterSummaryResponse getFriendRosterSummary(long tenantId, long accountId) { + public GetFriendRosterSummaryResponse getFriendRosterSummary(long tenantId, String accountId) { return callStub() .getFriendRosterSummary( GetFriendRosterSummaryRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(JwtClaims.requireCanonicalAccountUuid(accountId, "accountId")) .build()); } - public GetFriendPresencePolicyResponse getFriendPresencePolicy(long tenantId, long accountId) { + public GetFriendPresencePolicyResponse getFriendPresencePolicy(long tenantId, String accountId) { return callStub() .getFriendPresencePolicy( GetFriendPresencePolicyRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(JwtClaims.requireCanonicalAccountUuid(accountId, "accountId")) .build()); } public UpdateFriendPresencePolicyResponse updateFriendPresencePolicy( long tenantId, - long accountId, + String accountId, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy visibilityPolicy) { return callStub() .updateFriendPresencePolicy( UpdateFriendPresencePolicyRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(JwtClaims.requireCanonicalAccountUuid(accountId, "accountId")) .setVisibilityPolicy(visibilityPolicy) .build()); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java index 60801b312c..b34a024a73 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 @@ -72,7 +72,7 @@ public TextCommandInterpretationResult handle(TextCommand command, SessionContex return usageFailure; } try { - numericAccountId(context); + requireCanonicalAccountUuid(context.accountId()); } catch (IllegalArgumentException ex) { return accountIdUnavailable(action); } @@ -182,11 +182,11 @@ private TextCommandInterpretationResult handleList( SessionContext context, FriendListFilter filter, String rawCommandText) { ListFriendsResponse response = filter == FriendListFilter.ALL - ? socialGroupsClient.listFriends(context.tenantId(), numericAccountId(context)) + ? socialGroupsClient.listFriends(context.tenantId(), context.accountId()) : socialGroupsClient.listFriends( - context.tenantId(), numericAccountId(context), mapRosterFilter(filter)); + context.tenantId(), context.accountId(), mapRosterFilter(filter)); if (response == null && filter != FriendListFilter.ALL) { - response = socialGroupsClient.listFriends(context.tenantId(), numericAccountId(context)); + response = socialGroupsClient.listFriends(context.tenantId(), context.accountId()); } if (response.hasError()) { String message = @@ -210,13 +210,13 @@ private TextCommandInterpretationResult handleList( private TextCommandInterpretationResult handleAdd( SessionContext context, ResolvedFriendTarget target, String rawCommandText) { - if (target.friendAccountId() == numericAccountId(context)) { + if (Objects.equals(target.friendAccountId(), context.accountId())) { return friendTargetError( "FRIEND_SELF_LINK_FORBIDDEN", "Cannot add or remove your own account as a friend"); } AddFriendResponse response = socialGroupsClient.addFriend( - context.tenantId(), numericAccountId(context), target.friendAccountId()); + context.tenantId(), context.accountId(), target.friendAccountId()); if (response.hasError() || !response.getSuccess()) { String message = response.hasError() && !response.getError().getMessage().isBlank() @@ -234,13 +234,13 @@ private TextCommandInterpretationResult handleAdd( private TextCommandInterpretationResult handleRemove( SessionContext context, ResolvedFriendTarget target, String rawCommandText) { - if (target.friendAccountId() == numericAccountId(context)) { + if (Objects.equals(target.friendAccountId(), context.accountId())) { return friendTargetError( "FRIEND_SELF_LINK_FORBIDDEN", "Cannot add or remove your own account as a friend"); } RemoveFriendResponse response = socialGroupsClient.removeFriend( - context.tenantId(), numericAccountId(context), target.friendAccountId()); + context.tenantId(), context.accountId(), target.friendAccountId()); if (response.hasError() || !response.getSuccess()) { String message = response.hasError() && !response.getError().getMessage().isBlank() @@ -260,7 +260,7 @@ private TextCommandInterpretationResult handleDetail( SessionContext context, ResolvedFriendTarget target, String rawCommandText) { GetFriendResponse response = socialGroupsClient.getFriend( - context.tenantId(), numericAccountId(context), target.friendAccountId()); + context.tenantId(), context.accountId(), target.friendAccountId()); if (response.hasError()) { String code = "NOT_FOUND".equalsIgnoreCase(response.getError().getCode()) @@ -294,8 +294,7 @@ private TextCommandInterpretationResult handleDetailByOrdinal( return invalidUsage("FRIENDS SHOW "); } GetFriendByOrdinalResponse response = - socialGroupsClient.getFriendByOrdinal( - context.tenantId(), numericAccountId(context), ordinal); + socialGroupsClient.getFriendByOrdinal(context.tenantId(), context.accountId(), ordinal); if (response.hasError()) { String code = "NOT_FOUND".equalsIgnoreCase(response.getError().getCode()) @@ -325,7 +324,7 @@ private TextCommandInterpretationResult handleDetailByOrdinal( private TextCommandInterpretationResult handleSummary( SessionContext context, String rawCommandText) { GetFriendRosterSummaryResponse response = - socialGroupsClient.getFriendRosterSummary(context.tenantId(), numericAccountId(context)); + socialGroupsClient.getFriendRosterSummary(context.tenantId(), context.accountId()); if (response.hasError()) { String message = response.getError().getMessage().isBlank() @@ -358,7 +357,7 @@ private TextCommandInterpretationResult handleSummary( private TextCommandInterpretationResult handleVisibilityView( SessionContext context, String rawCommandText) { GetFriendPresencePolicyResponse response = - socialGroupsClient.getFriendPresencePolicy(context.tenantId(), numericAccountId(context)); + socialGroupsClient.getFriendPresencePolicy(context.tenantId(), context.accountId()); if (response.hasError()) { String code = response.getError().getCode().isBlank() @@ -392,7 +391,7 @@ private TextCommandInterpretationResult handleVisibilityUpdate( } UpdateFriendPresencePolicyResponse response = socialGroupsClient.updateFriendPresencePolicy( - context.tenantId(), numericAccountId(context), visibilityPolicy); + context.tenantId(), context.accountId(), visibilityPolicy); if (response.hasError() || !response.getSuccess()) { String code = response.hasError() && !response.getError().getCode().isBlank() @@ -423,8 +422,7 @@ private TextCommandInterpretationResult handleRemoveByOrdinal( return invalidUsage("FRIENDS REMOVE "); } RemoveFriendByOrdinalResponse response = - socialGroupsClient.removeFriendByOrdinal( - context.tenantId(), numericAccountId(context), ordinal); + socialGroupsClient.removeFriendByOrdinal(context.tenantId(), context.accountId(), ordinal); if (response.hasError() || !response.getSuccess()) { String code = response.hasError() && "NOT_FOUND".equalsIgnoreCase(response.getError().getCode()) @@ -511,7 +509,7 @@ private FriendPresenceViewOutput toView(ListFriendsResponse response, FriendList private FriendPresenceViewOutput.Entry toEntry(int ordinal, FriendRosterEntry entry) { FriendPresenceEntry presence = entry.getPresence(); - long friendAccountId = requireFriendAccountId(entry.getFriendAccountId()); + String friendAccountId = requireFriendAccountId(entry.getFriendAccountId()); String characterName = presence.getCharacterName().isBlank() ? null : presence.getCharacterName().trim(); return new FriendPresenceViewOutput.Entry( @@ -544,23 +542,19 @@ private String activityState(FriendPresenceActivityState activityState) { }; } - private long requireFriendAccountId(String value) { - if (!StringUtils.hasText(value)) { + private String requireFriendAccountId(String value) { + if (!SessionContext.isCanonicalAccountIdentity(value)) { throw new IllegalStateException( - "Malformed friend roster friendAccountId: friendAccountId is required"); - } - try { - return PositiveLongParsing.requireOptionalText(value, "friendAccountId") - .orElseThrow(() -> new IllegalArgumentException("friendAccountId is required")); - } catch (IllegalArgumentException ex) { - throw new IllegalStateException( - "Malformed friend roster friendAccountId: " + ex.getMessage(), ex); + "Malformed friend roster friendAccountId: " + + "friendAccountId must be a canonical non-nil UUID"); } + return value; } - private long numericAccountId(SessionContext context) { - return PositiveLongParsing.requireOptionalText(context.accountId(), "accountId") - .orElseThrow(() -> new IllegalArgumentException("accountId must be positive")); + private void requireCanonicalAccountUuid(String value) { + if (!SessionContext.isCanonicalAccountIdentity(value)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } } private Long parseOptionalLong(String value) { @@ -662,13 +656,21 @@ private FriendAction parseAction(TextCommand command) { } private ResolvedFriendTarget resolveTarget(SessionContext context, FriendAction action) { - Long accountId = tryParseAccountId(action.targetToken()); + String accountId = tryParseAccountId(action.targetToken()); if (accountId != null) { return new ResolvedFriendTarget(accountId, null, null); } + if (isNumericAccountId(action.targetToken()) || looksLikeAccountUuid(action.targetToken())) { + return new ResolvedFriendTarget( + null, + null, + friendTargetError( + "INVALID_ARGUMENT", + "Friend account ID must be a canonical non-nil UUID or a character name")); + } if (!StringUtils.hasText(action.targetToken())) { return new ResolvedFriendTarget( - 0L, + null, null, invalidUsage("FRIENDS " + action.keyword() + " ")); } @@ -677,17 +679,16 @@ private ResolvedFriendTarget resolveTarget(SessionContext context, FriendAction context, resolvePlayableStateScope(context), action.targetToken().trim()); if (character.isEmpty() || !StringUtils.hasText(character.get().getAccountId())) { return new ResolvedFriendTarget( - 0L, + null, null, friendTargetError("FRIEND_TARGET_NOT_FOUND", notFoundMessage(action.targetToken()))); } - PositiveLongParsing.ParsedPositiveLong parsedAccountId = - PositiveLongParsing.parseOptionalText(character.get().getAccountId(), "friendAccountId"); - if (!parsedAccountId.valid()) { + String resolvedAccountId = character.get().getAccountId(); + if (!SessionContext.isCanonicalAccountIdentity(resolvedAccountId)) { return new ResolvedFriendTarget( - 0L, null, malformedResolvedTargetError(action, character.get().getAccountId())); + null, null, malformedResolvedTargetError(action, resolvedAccountId)); } - return new ResolvedFriendTarget(parsedAccountId.value(), character.get().getName(), null); + return new ResolvedFriendTarget(resolvedAccountId, character.get().getName(), null); } private TextCommandInterpretationResult malformedResolvedTargetError( @@ -769,10 +770,16 @@ private FriendRosterFilter mapRosterFilter(FriendListFilter filter) { }; } - private Long tryParseAccountId(String value) { - return PositiveLongParsing.parseOptionalText(value, "friendAccountId") - .optionalValue() - .orElse(null); + private String tryParseAccountId(String value) { + return SessionContext.isCanonicalAccountIdentity(value) ? value : null; + } + + private boolean isNumericAccountId(String value) { + return value != null && value.matches("[+-]?\\d+"); + } + + private boolean looksLikeAccountUuid(String value) { + return value != null && value.matches("(?i)[0-9a-f-]{36}"); } private boolean isOrdinalToken(String value) { @@ -947,5 +954,5 @@ private record FriendAction( String invalidUsage) {} private record ResolvedFriendTarget( - long friendAccountId, String characterName, TextCommandInterpretationResult errorResult) {} + String friendAccountId, String characterName, TextCommandInterpretationResult errorResult) {} } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java index 7b6c50b189..15e7ffd123 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java @@ -10,6 +10,7 @@ import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpResponse; import net.firedevops.firemud.common.EmailCanonicalization; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.entity.GameInstance; @@ -21,7 +22,6 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; -import net.firedevops.firemud.gamesession.service.PositiveLongParsing; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; @@ -159,8 +159,8 @@ public LoginCommandHandlingResult handle( return failure(errorCode, publicErrorMessage(error, errorCode)); } - Long authenticatedAccountId = parseAccountId(authResponse.getAccountId()); - if (authenticatedAccountId == null || authenticatedAccountId <= 0) { + String authenticatedAccountId = parseAccountId(authResponse.getAccountId()); + if (authenticatedAccountId == null) { clearFailedLoginSessionState( numericSessionId, instance.getTenantId(), bootstrapGameInstanceId, null, null, 0L); return invalidAccountFailure(); @@ -240,7 +240,7 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionI private void persistSessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, String jwt, long bootstrapGameInstanceId) { @@ -255,7 +255,7 @@ private void persistSessionContext( projectedExisting != null && projectedExisting.tenantId() == tenantId ? projectedExisting : null; - String accountIdText = Long.toString(accountId); + String accountIdText = accountId; boolean sameAuthenticatedAccount = existing != null && Objects.equals(existing.accountId(), accountIdText); Optional reusableBootstrapShell = @@ -347,14 +347,14 @@ private Optional reusableBootstrapShell( private SessionContext authenticatedBootstrapContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, String jwt, SessionContext bootstrapShell) { return new SessionContext( sessionId, tenantId, - Long.toString(accountId), + accountId, loginName, 0L, null, @@ -532,13 +532,12 @@ private SessionIdParsing.ParsedSessionId parseSessionId(String sessionIdText) { return SessionIdParsing.parse(sessionIdText); } - private Long parseAccountId(String accountIdText) { - PositiveLongParsing.ParsedPositiveLong parsed = - PositiveLongParsing.parseOptionalText(accountIdText, "accountId"); - if (!parsed.valid()) { + private String parseAccountId(String accountIdText) { + try { + return JwtClaims.requireCanonicalAccountUuid(accountIdText, "accountId"); + } catch (IllegalArgumentException ex) { return null; } - return parsed.value(); } private LoginCommandHandlingResult invalidSessionFailure(String message) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index c86cc986dd..ca91d17ae4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -3,6 +3,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; +import java.time.Duration; import java.time.Instant; import java.time.format.DateTimeParseException; import java.util.HashSet; @@ -381,11 +382,14 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { private Optional validateModerationPolicy( SessionContext context, GameplayWorldCatalog.RealmView selectedRealm, String tenantTag) { + if (!SessionContext.isCanonicalAccountIdentity(context.accountId())) { + return Optional.of( + authorityUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), context.characterId())); + } var decision = moderationPolicyClient.evaluateGameplayAdmission( - selectedRealm.tenantId(), - PositiveLongParsing.requireOptionalText(context.accountId(), "accountId") - .orElseThrow(() -> new IllegalArgumentException("accountId must be positive"))); + selectedRealm.tenantId(), context.accountId()); if (decision.hasError() && decision.getError().getCode() != null && !decision.getError().getCode().isBlank()) { @@ -743,7 +747,17 @@ private Optional validateMembershipResponse( authorityUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } - if (grantError.isPresent() || !grantResponse.getGranted()) { + if (grantError.isPresent()) { + return Optional.of( + worldAccessDeniedFailure( + context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); + } + if (!isSafeRealmGrantResponse(grantResponse, context, selectedWorld, selectedRealm)) { + return Optional.of( + authorityUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); + } + if (!grantResponse.getGranted()) { return Optional.of( worldAccessDeniedFailure( context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); @@ -753,6 +767,30 @@ private Optional validateMembershipResponse( return Optional.empty(); } + private boolean isSafeRealmGrantResponse( + GetRealmAccessGrantForRuntimeResponse response, + SessionContext context, + GameplayWorldCatalog.WorldView selectedWorld, + GameplayWorldCatalog.RealmView selectedRealm) { + if (!SessionContext.isCanonicalAccountIdentity(response.getAccountId()) + || !context.accountId().equals(response.getAccountId()) + || !Long.toString(selectedRealm.tenantId()).equals(response.getTenantId()) + || !selectedWorld.slug().equals(response.getWorldSlug()) + || !selectedRealm.slug().equals(response.getRealmSlug()) + || (response.getGranted() && response.getGrantVersion() <= 0L) + || !StringUtils.hasText(response.getEvaluatedAt())) { + return false; + } + try { + Instant evaluatedAt = Instant.parse(response.getEvaluatedAt()); + Instant now = Instant.now(); + return !evaluatedAt.isAfter(now.plusSeconds(5)) + && !evaluatedAt.isBefore(now.minus(Duration.ofMinutes(5))); + } catch (DateTimeParseException ex) { + return false; + } + } + private PlayCommandHandlingResult worldAccessDeniedFailure( SessionContext context, String tenantTag, @@ -919,8 +957,9 @@ private boolean isSafeMembershipAuthorityResponse( } try { Instant.parse(response.getEvaluatedAt()); - if (!PositiveLongParsing.requireOptionalText(response.getAccountId(), "accountId") - .equals(PositiveLongParsing.requireOptionalText(context.accountId(), "accountId")) + if (!SessionContext.isCanonicalAccountIdentity(response.getAccountId()) + || !SessionContext.isCanonicalAccountIdentity(context.accountId()) + || !response.getAccountId().equals(context.accountId()) || Long.parseLong(response.getTenantId()) != selectedRealm.tenantId()) { return false; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 43abe253c4..222a1dd56b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -40,6 +40,9 @@ public java.util.Optional browseRealms(String worldSelect public CharacterBrowseResult browseCharacters( SessionContext sessionContext, String worldSelector, String realmSelector) { Objects.requireNonNull(sessionContext, "sessionContext must not be null"); + if (!sessionContext.hasAccountIdentity()) { + return CharacterBrowseResult.unavailable(); + } java.util.Optional maybeWorld = worldCatalog.resolveWorld(worldSelector); if (maybeWorld.isEmpty()) { @@ -73,6 +76,10 @@ public CharacterBrowseResult browseCharacters( new java.util.ArrayList<>(response.getCharactersCount()); for (int i = 0; i < response.getCharactersCount(); i++) { net.firedevops.firemud.entitymanagement.v1.Character character = response.getCharacters(i); + if (!sessionContext.accountId().equals(character.getAccountId()) + || !Long.toString(realm.tenantId()).equals(character.getTenantId())) { + return CharacterBrowseResult.unavailable(); + } entries.add( new CharacterBrowseViewOutput.CharacterEntry( i + 1, character.getId(), character.getName(), character.getLevel())); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java index 95621033df..9b31c88226 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java @@ -18,7 +18,7 @@ public final class GameplayLocalPathReadinessProbe { private static final long PROBE_TENANT_ID = 0L; private static final long PROBE_SESSION_ID = 9_223_372_036_854_770_000L; - private static final long PROBE_ACCOUNT_ID = 9_223_372_036_854_770_001L; + private static final String PROBE_ACCOUNT_ID = "00000000-0000-4000-8000-000000000001"; private static final long PROBE_CHARACTER_ID = 9_223_372_036_854_770_002L; private static final long PROBE_GAME_INSTANCE_ID = 0L; private static final String PROBE_ROOM_INSTANCE_ID_PREFIX = "readiness-room-"; @@ -44,7 +44,7 @@ public ProbeResult probeSessionContextStore() { new SessionContext( probeSessionId, PROBE_TENANT_ID, - Long.toString(PROBE_ACCOUNT_ID), + PROBE_ACCOUNT_ID, PROBE_CHARACTER_ID, PROBE_GAME_INSTANCE_ID, probeRoomInstanceId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendMutationResultOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendMutationResultOutput.java index 0bd9a89cfd..c17bf5c6f9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendMutationResultOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendMutationResultOutput.java @@ -4,7 +4,11 @@ /** Structured payload for canonical friend add/remove mutation results. */ public record FriendMutationResultOutput( - String action, long friendAccountId, String displayName, String characterName, Integer ordinal) + String action, + String friendAccountId, + String displayName, + String characterName, + Integer ordinal) implements PlayerOutputPayload { public FriendMutationResultOutput { Objects.requireNonNull(action, "action must not be null"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java index b31bff8ecb..a7e564dd09 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/FriendPresenceViewOutput.java @@ -12,7 +12,7 @@ public record FriendPresenceViewOutput( public record Entry( int ordinal, Long friendLinkId, - long friendAccountId, + String friendAccountId, String status, Long linkedAtEpochMs, String displayName, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java index 0ebff77e98..f14a5f3963 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java @@ -92,6 +92,9 @@ public Optional resolveByGameplayName( public SessionContext normalizeResolvedContext(SessionContext context) { Objects.requireNonNull(context, "context must not be null"); + if (context.accountId() != null && !context.hasAccountIdentity()) { + return context; + } SessionContext normalized = sessionRoutingNormalizationService.normalizeProjectedContext(context); if (normalized.equals(context)) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java index dc064587b7..e61bc220d6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java @@ -4,7 +4,7 @@ import java.util.Locale; import java.util.Objects; import java.util.Optional; -import org.springframework.util.StringUtils; +import net.firedevops.firemud.common.security.JwtClaims; /** Represents persisted login context stored in Redis for a session. */ public record SessionContext( @@ -323,8 +323,20 @@ public boolean hasGameplayIdentity() { return gameInstanceId > 0 && characterId > 0; } + /** + * Uses the shared ordinary Account identity contract without interpreting private row handles. + */ + public static boolean isCanonicalAccountIdentity(String accountId) { + try { + JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); + return true; + } catch (IllegalArgumentException ex) { + return false; + } + } + public boolean hasAccountIdentity() { - return StringUtils.hasText(accountId); + return isCanonicalAccountIdentity(accountId); } public boolean hasGameplayBinding() { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java index 3c4a0e5084..a46505eafe 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java @@ -22,6 +22,7 @@ import net.firedevops.firemud.gamesession.service.GameplayPresenceActivityResolver; import net.firedevops.firemud.gamesession.service.GameplayPresenceActivityState; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; +import net.firedevops.firemud.gamesession.service.SessionContext; import org.springframework.stereotype.Service; @Service @@ -59,11 +60,17 @@ public AccountPresenceQueryServiceImpl( public List queryAccountPresence( long tenantId, String viewerAccountId, List accountIds) { Objects.requireNonNull(accountIds, "accountIds"); + if (!SessionContext.isCanonicalAccountIdentity(viewerAccountId)) { + throw new IllegalArgumentException( + "viewerAccountId must be a canonical non-nil Account UUID"); + } LinkedHashSet requestedIds = new LinkedHashSet<>(); for (String accountId : accountIds) { - if (accountId != null && !accountId.isBlank()) { - requestedIds.add(accountId); + if (!SessionContext.isCanonicalAccountIdentity(accountId)) { + throw new IllegalArgumentException( + "accountIds must contain canonical non-nil Account UUIDs"); } + requestedIds.add(accountId); } if (requestedIds.isEmpty()) { return List.of(); @@ -74,18 +81,22 @@ public List queryAccountPresence( Map recentStates = accountRecentPresenceService.findByAccountIds(tenantId, requestedIds); for (String accountId : requestedIds) { - results.put( - accountId, - offline(tenantId, accountId, recentStates.get(accountId), currentRuntimePointers)); + AccountRecentPresenceState recentState = + matchingRecentState(tenantId, accountId, recentStates.get(accountId)); + results.put(accountId, offline(tenantId, accountId, recentState, currentRuntimePointers)); } Map> activePresences = gameplayPresenceService.listConnectedByAccountIds(tenantId, requestedIds); for (Map.Entry> entry : activePresences.entrySet()) { String accountId = entry.getKey(); + if (!requestedIds.contains(accountId) + || !SessionContext.isCanonicalAccountIdentity(accountId)) { + continue; + } GameplayPresence presence = selectCurrentPresence(tenantId, entry.getValue(), currentRuntimePointers); - if (presence == null) { + if (presence == null || !accountId.equals(presence.accountId())) { continue; } GameplayPresenceActivityState activityState = @@ -93,7 +104,8 @@ public List queryAccountPresence( GameplayAdmissionPointerSnapshot pointer = currentRuntimePointer(tenantId, presence.gameInstanceId(), currentRuntimePointers) .orElse(null); - AccountRecentPresenceState recentState = recentStates.get(accountId); + AccountRecentPresenceState recentState = + matchingRecentState(tenantId, accountId, recentStates.get(accountId)); Long currentGameInstanceId = pointer == null ? presence.gameInstanceId() : pointer.gameInstanceId(); String currentPlayableStateScope = @@ -127,6 +139,17 @@ public List queryAccountPresence( return List.copyOf(new ArrayList<>(results.values())); } + private AccountRecentPresenceState matchingRecentState( + long tenantId, String accountId, AccountRecentPresenceState recentState) { + if (recentState == null + || recentState.tenantId() != tenantId + || !accountId.equals(recentState.accountId()) + || !SessionContext.isCanonicalAccountIdentity(recentState.accountId())) { + return null; + } + return recentState; + } + private GameplayPresence selectCurrentPresence( long tenantId, List presences, @@ -145,7 +168,10 @@ private boolean isCurrentPresence( long tenantId, GameplayPresence presence, Map currentRuntimePointers) { - if (presence == null || presence.tenantId() != tenantId || presence.gameInstanceId() <= 0) { + if (presence == null + || !SessionContext.isCanonicalAccountIdentity(presence.accountId()) + || presence.tenantId() != tenantId + || presence.gameInstanceId() <= 0) { return false; } GameplayAdmissionPointerSnapshots.RoutingBundle routingBundle = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java index 1c89763768..5e3f2d9ce7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java @@ -19,7 +19,6 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; -import net.firedevops.firemud.gamesession.service.PositiveLongParsing; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -100,12 +99,12 @@ public CommandEnqueueResult enqueue( } var sessionContext = resolveSessionContext(sessionIdText); - Optional numericAccountId; + Optional accountUuid; try { - numericAccountId = + accountUuid = sessionContext .map(SessionContext::accountId) - .flatMap(id -> PositiveLongParsing.requireOptionalText(id, "accountId")); + .map(CommandServiceImpl::requireCanonicalAccountUuid); } catch (IllegalArgumentException ex) { return CommandEnqueueResult.failure("INVALID_ARGUMENT", ex.getMessage()); } @@ -158,7 +157,7 @@ public CommandEnqueueResult enqueue( requiresSoloTick, queueTarget.get(), sessionContext, - numericAccountId, + accountUuid, authoredAdmission, runtimeScope.get()); logger.info( @@ -200,7 +199,7 @@ private GameplayCommand persistAcceptedCommand( boolean requiresSoloTick, QueueTarget queueTarget, Optional sessionContext, - Optional numericAccountId, + Optional accountUuid, AuthoredCommandAdmission authoredAdmission, RuntimeRegionStatus runtimeScope) { Instant now = Instant.now(); @@ -209,7 +208,7 @@ private GameplayCommand persistAcceptedCommand( gameplayCommand.setTenantId(queueTarget.tenantId()); gameplayCommand.setGameInstanceId(queueTarget.queueTargetId()); gameplayCommand.setSessionId(sessionId); - numericAccountId.ifPresent(gameplayCommand::setAccountId); + accountUuid.ifPresent(gameplayCommand::setAccountUuid); sessionContext .map(SessionContext::characterId) .filter(id -> id > 0) @@ -440,4 +439,11 @@ private Optional resolveRuntimeScope(QueueTarget queueTarge private static String blankToNull(String value) { return value == null || value.isBlank() ? null : value; } + + private static UUID requireCanonicalAccountUuid(String value) { + if (!SessionContext.isCanonicalAccountIdentity(value)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + return UUID.fromString(value); + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionCommandControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionCommandControlPlaneService.java index fdd924dba7..fa20fab5bb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionCommandControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionCommandControlPlaneService.java @@ -1545,8 +1545,10 @@ private GameplayCommandStatus toStatus(GameplayCommand command) { .setLastAttemptAtMs(toEpochMillis(command.getLastAttemptAt())) .setAttemptCount(command.getAttemptCount()) .setPlayableStateScope(toPlayableStateScopeStatus(command.getPlayableStateScope())); - if (command.getAccountId() != null) { - builder.setAccountId(command.getAccountId().toString()); + if (command.getAccountUuid() != null + && net.firedevops.firemud.gamesession.service.SessionContext.isCanonicalAccountIdentity( + command.getAccountUuid().toString())) { + builder.setAccountId(command.getAccountUuid().toString()); } if (command.getCharacterId() != null) { builder.setCharacterId(command.getCharacterId().toString()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 52924dfb0b..544602d8d1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -372,11 +372,17 @@ private long parseOwnerAccountId(String ownerAccountIdText) { return ControlPlaneRequestParser.parsePositiveLong(ownerAccountIdText, "ownerAccountId"); } - private List parseAccountIds(List accountIds) { + private String parsePresenceAccountId(String accountId, String fieldName) { + if (!net.firedevops.firemud.gamesession.service.SessionContext.isCanonicalAccountIdentity( + accountId)) { + throw new IllegalArgumentException(fieldName + " must be a canonical non-nil Account UUID"); + } + return accountId; + } + + private List parsePresenceAccountIds(List accountIds) { return accountIds.stream() - .map( - accountId -> - Long.toString(ControlPlaneRequestParser.parsePositiveLong(accountId, "accountId"))) + .map(accountId -> parsePresenceAccountId(accountId, "accountId")) .toList(); } @@ -579,16 +585,16 @@ public void queryAccountPresence( try { long tenantId = ControlPlaneRequestParser.parsePositiveLong(request.getTenantId(), "tenantId"); - long viewerAccountId = parseOwnerAccountId(request.getViewerAccountId()); + String viewerAccountId = + parsePresenceAccountId(request.getViewerAccountId(), "viewerAccountId"); requireTenantOrCurrentAccountAccess(tenantId, viewerAccountId); if (request.getAccountIdsCount() > 100) { throw new IllegalArgumentException("accountIds must contain at most 100 entries"); } - List accountIds = parseAccountIds(request.getAccountIdsList()); + List accountIds = parsePresenceAccountIds(request.getAccountIdsList()); QueryAccountPresenceResponse.Builder builder = QueryAccountPresenceResponse.newBuilder(); for (var snapshot : - accountPresenceQueryService.queryAccountPresence( - tenantId, Long.toString(viewerAccountId), accountIds)) { + accountPresenceQueryService.queryAccountPresence(tenantId, viewerAccountId, accountIds)) { AccountPresenceEntry.Builder entry = AccountPresenceEntry.newBuilder() .setAccountId(snapshot.accountId()) @@ -931,8 +937,12 @@ private void requireTenantAccess(long tenantId) { throw new AuthorizationException("Tenant access required"); } - private void requireTenantOrCurrentAccountAccess(long tenantId, long accountId) { - if (SessionContext.hasTenantAccess(tenantId) || isCurrentAccount(accountId)) { + private void requireTenantOrCurrentAccountAccess(long tenantId, String accountId) { + String currentAccountId = SessionContext.getAccountId(); + if (SessionContext.hasTenantAccess(tenantId) + || (net.firedevops.firemud.gamesession.service.SessionContext.isCanonicalAccountIdentity( + currentAccountId) + && currentAccountId.equals(accountId))) { return; } throw new AuthorizationException("Account access required"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java index dd83268e9e..ea7d320585 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java @@ -67,7 +67,9 @@ public RedisAccountRecentPresenceService( @Override public void recordConnected(SessionContext context) { - if (context == null || context.tenantId() <= 0 || !context.hasAccountIdentity()) { + if (context == null + || context.tenantId() <= 0 + || !SessionContext.isCanonicalAccountIdentity(context.accountId())) { return; } GameplayPresence presence = @@ -113,13 +115,16 @@ public Map findByAccountIds( ValueOperations valueOps = redisTemplate.opsForValue(); LinkedHashMap results = new LinkedHashMap<>(); for (String accountId : accountIds) { - if (accountId == null || accountId.isBlank() || valueOps == null) { + if (!SessionContext.isCanonicalAccountIdentity(accountId) || valueOps == null) { continue; } try { AccountRecentPresenceState state = (AccountRecentPresenceState) valueOps.get(key(tenantId, accountId)); - if (state != null) { + if (state != null + && state.tenantId() == tenantId + && accountId.equals(state.accountId()) + && SessionContext.isCanonicalAccountIdentity(state.accountId())) { results.put(accountId, state); } } catch (SerializationException | ClassCastException ex) { @@ -132,7 +137,10 @@ public Map findByAccountIds( private void write( RoutingSnapshot snapshot, AccountRecentPresenceDisposition disposition, long timestampMs) { ValueOperations valueOps = redisTemplate.opsForValue(); - if (valueOps == null || snapshot == null) { + if (valueOps == null + || snapshot == null + || snapshot.tenantId() <= 0 + || !SessionContext.isCanonicalAccountIdentity(snapshot.accountId())) { return; } String key = key(snapshot.tenantId(), snapshot.accountId()); @@ -165,9 +173,14 @@ public WriteAttemptResult execute(RedisOperations operations) { operations.unwatch(); return WriteAttemptResult.PRESERVED; } - if (retained != null && !(retained instanceof AccountRecentPresenceState)) { - operations.unwatch(); - return WriteAttemptResult.PRESERVED; + if (retained != null) { + if (!(retained instanceof AccountRecentPresenceState retainedState) + || retainedState.tenantId() != snapshot.tenantId() + || !snapshot.accountId().equals(retainedState.accountId()) + || !SessionContext.isCanonicalAccountIdentity(retainedState.accountId())) { + operations.unwatch(); + return WriteAttemptResult.PRESERVED; + } } operations.multi(); operations.opsForValue().set(key, state, ttl); @@ -184,7 +197,9 @@ public WriteAttemptResult execute(RedisOperations operations) { } private RoutingSnapshot routingSnapshot(SessionContext context, GameplayPresence presence) { - if (context == null || context.tenantId() <= 0 || !context.hasAccountIdentity()) { + if (context == null + || context.tenantId() <= 0 + || !SessionContext.isCanonicalAccountIdentity(context.accountId())) { return null; } GameplayPresence effectivePresence = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java index 61deba6f1e..dc63ddf28e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java @@ -81,11 +81,14 @@ public FirstPartyConnectContext requireRetained(FirstPartyConnectContext context public void unregister(long sessionId) { String key = key(sessionId); try { - if (valueOperations().get(key) instanceof FirstPartyConnectContext) { + if (valueOperations().get(key) instanceof FirstPartyConnectContext context) { + // Delete only a verified, complete retained handoff; incompatible evidence is retained. + contextService.requireRetained(context); redisTemplate.delete(key); } - } catch (SerializationException | ClassCastException ex) { - // Retain unreadable evidence instead of treating it as an absent context. + } catch (SerializationException | ClassCastException | IllegalStateException ex) { + // Retain unreadable, incomplete or unverifiable evidence instead of treating it as an absent + // context. } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java index 153dfc047d..fed4b5a38e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java @@ -71,7 +71,10 @@ public RedisGameplayPresenceService( @Override public void registerConnected(SessionContext context) { - if (context == null || context.tenantId() <= 0 || context.gameInstanceId() <= 0) { + if (context == null + || !SessionContext.isCanonicalAccountIdentity(context.accountId()) + || context.tenantId() <= 0 + || context.gameInstanceId() <= 0) { return; } ValueOperations valueOps = redisTemplate.opsForValue(); @@ -221,6 +224,9 @@ public List listConnectedByGameInstance(long tenantId, long ga setOps.remove(gameInstanceKey, sessionIdText); continue; } + if (!SessionContext.isCanonicalAccountIdentity(presence.accountId())) { + continue; + } if (presence.tenantId() == tenantId && presence.gameInstanceId() == gameInstanceId) { matches.add(presence); } @@ -246,7 +252,7 @@ public Map> listConnectedByAccountIds( LinkedHashMap> matches = new LinkedHashMap<>(); for (String accountId : accountIds) { - if (accountId == null || accountId.isBlank()) { + if (!SessionContext.isCanonicalAccountIdentity(accountId)) { continue; } String accountKey = accountKey(tenantId, accountId); @@ -272,6 +278,9 @@ public Map> listConnectedByAccountIds( setOps.remove(accountKey, sessionIdText); continue; } + if (!SessionContext.isCanonicalAccountIdentity(presence.accountId())) { + continue; + } if (presence.tenantId() != tenantId || !java.util.Objects.equals(presence.accountId(), accountId)) { setOps.remove(accountKey, sessionIdText); @@ -291,7 +300,8 @@ public Map> listConnectedByAccountIds( public Optional findConnectedBySessionId(long sessionId) { ValueOperations valueOps = redisTemplate.opsForValue(); try { - return Optional.ofNullable((GameplayPresence) valueOps.get(presenceKey(sessionId))); + return Optional.ofNullable((GameplayPresence) valueOps.get(presenceKey(sessionId))) + .filter(presence -> SessionContext.isCanonicalAccountIdentity(presence.accountId())); } catch (SerializationException | ClassCastException ex) { return Optional.empty(); } @@ -304,7 +314,12 @@ private String presenceKey(long sessionId) { private GameplayPresence readRetainedPresenceForMutation( ValueOperations valueOps, String presenceKey) { try { - return (GameplayPresence) valueOps.get(presenceKey); + GameplayPresence presence = (GameplayPresence) valueOps.get(presenceKey); + if (presence != null && !SessionContext.isCanonicalAccountIdentity(presence.accountId())) { + throw new IllegalStateException( + "Retained gameplay presence has an invalid Account UUID; mutation aborted"); + } + return presence; } catch (SerializationException | ClassCastException ex) { throw new IllegalStateException( "Retained gameplay presence is unreadable or incompatible; mutation aborted", ex); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java index ffcfdb386f..7a765efaa7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java @@ -37,6 +37,10 @@ public RedisSessionContextService( @Override public void save(SessionContext context) { + if (context.accountId() != null && !context.hasAccountIdentity()) { + throw new IllegalArgumentException( + "Session context requires a canonical non-nil Account UUID"); + } for (int attempt = 0; attempt < MAX_SAVE_RETRIES; attempt++) { Boolean committed = redisTemplate.execute( @@ -212,12 +216,22 @@ private List watchKeys(SessionContext context) { private SessionContext readContext( org.springframework.data.redis.core.RedisOperations operations, String key) { - return (SessionContext) operations.opsForValue().get(key); + SessionContext context = (SessionContext) operations.opsForValue().get(key); + if (context != null && context.accountId() != null && !context.hasAccountIdentity()) { + throw new SessionContextUnavailableException( + "Retained session context has a non-canonical Account identity", null); + } + return context; } private Optional findContextForLookup(String key) { try { - return Optional.ofNullable((SessionContext) redisTemplate.opsForValue().get(key)); + SessionContext context = (SessionContext) redisTemplate.opsForValue().get(key); + if (context != null && context.accountId() != null && !context.hasAccountIdentity()) { + throw new SessionContextUnavailableException( + "Retained session context has a non-canonical Account identity", null); + } + return Optional.ofNullable(context); } catch (SerializationException | ClassCastException ex) { throw new SessionContextUnavailableException("Retained session context is unreadable", ex); } 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 b2dc4d25d6..0da784abf2 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 @@ -20,6 +20,7 @@ import net.firedevops.firemud.socialgroups.v1.FriendPresenceActivityState; import net.firedevops.firemud.socialgroups.v1.FriendPresenceEntry; import net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy; +import net.firedevops.firemud.test.AccountRuntimeStubServer; import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; @@ -39,6 +40,10 @@ class CommunicationWebSocketCrossServiceTest { private static final long ACCOUNT_ID = ChatTestFixtures.EMBERLINE_ACCOUNT_ROW_ID; private static final long SORA_ACCOUNT_ID = ChatTestFixtures.SORA_ACCOUNT_ROW_ID; private static final long NYX_ACCOUNT_ID = ChatTestFixtures.NYX_ACCOUNT_ROW_ID; + private static final String ACCOUNT_UUID = + AccountRuntimeStubServer.accountUuidForTestFixture(ACCOUNT_ID); + private static final String SORA_ACCOUNT_UUID = + AccountRuntimeStubServer.accountUuidForTestFixture(SORA_ACCOUNT_ID); private static final long DEMO_WORLD_INSTANCE_ID = 1L; private static final String READY_LOOK_TEXT = "Candle-lit Antechamber"; @@ -193,7 +198,7 @@ void websocketFriendsShowsCanonicalCrossGamePresence() throws Exception { runCommunicationSequence( sessionId, "FRIENDS", - "Sora [acct #" + SORA_ACCOUNT_ID + "] - online in Demo World / Live Realm (idle)"); + "Sora [acct #" + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)"); assertThat(responses).hasSizeGreaterThanOrEqualTo(3); assertThat(responses) @@ -201,10 +206,10 @@ void websocketFriendsShowsCanonicalCrossGamePresence() throws Exception { response -> response.contains( "Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)")); GameplaySocialAssertions.assertListFriendsRequest( - socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), Long.toString(ACCOUNT_ID)); + socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); } @Test @@ -218,7 +223,7 @@ void websocketFriendsOnlineFiltersCanonicalRoster() throws Exception { "FRIENDS ONLINE", "Friends ONLINE [1/1]:\n" + "1) Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)"); assertThat(responses) @@ -227,12 +232,12 @@ void websocketFriendsOnlineFiltersCanonicalRoster() throws Exception { response.contains("Friends ONLINE [1/1]:") && response.contains( "1) Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)")); GameplaySocialAssertions.assertListFriendsRequest( socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), + ACCOUNT_UUID, net.firedevops.firemud.socialgroups.v1.FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); } @@ -247,7 +252,7 @@ void websocketFriendsSharedFiltersCanonicalRoster() throws Exception { "FRIENDS SHARED", "Friends SHARED [1/1]:\n" + "1) Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)"); assertThat(responses) @@ -256,12 +261,12 @@ void websocketFriendsSharedFiltersCanonicalRoster() throws Exception { response.contains("Friends SHARED [1/1]:") && response.contains( "1) Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)")); GameplaySocialAssertions.assertListFriendsRequest( socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), + ACCOUNT_UUID, net.firedevops.firemud.socialgroups.v1.FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED); } @@ -276,14 +281,14 @@ void freshGameplayBaselineReappliesConfiguredFriendPresenceBaseline() throws Exc runCommunicationSequence( sessionId, "FRIENDS", - "Sora [acct #" + SORA_ACCOUNT_ID + "] - online in Demo World / Live Realm (idle)"); + "Sora [acct #" + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)"); assertThat(responses) .anyMatch( response -> response.contains( "Sora [acct #" - + SORA_ACCOUNT_ID + + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)")); } @@ -327,22 +332,22 @@ void websocketFriendsMutationFlowUsesCanonicalRosterSurface() throws Exception { try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-mutate-conn")) { - client.send("FRIENDS ADD 77"); - client.awaitContains("Friend #77 added."); - client.send("FRIENDS REMOVE 77"); - client.awaitContains("Friend #77 removed."); + client.send("FRIENDS ADD " + SORA_ACCOUNT_UUID); + client.awaitContains("Friend #" + SORA_ACCOUNT_UUID + " added."); + client.send("FRIENDS REMOVE " + SORA_ACCOUNT_UUID); + client.awaitContains("Friend #" + SORA_ACCOUNT_UUID + " removed."); } GameplaySocialAssertions.assertAddFriendRequest( socialStub().lastAddFriendRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - "77"); + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); GameplaySocialAssertions.assertRemoveFriendRequest( socialStub().lastRemoveFriendRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - "77"); + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); } @Test @@ -353,21 +358,21 @@ void websocketFriendsMutationByCharacterNameUsesCanonicalIdentityLookup() throws try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-mutate-name-conn")) { client.send("FRIENDS ADD Sora"); - client.awaitContains("Sora [acct #" + SORA_ACCOUNT_ID + "] added."); + client.awaitContains("Sora [acct #" + SORA_ACCOUNT_UUID + "] added."); client.send("FRIENDS REMOVE Sora"); - client.awaitContains("Sora [acct #" + SORA_ACCOUNT_ID + "] removed."); + client.awaitContains("Sora [acct #" + SORA_ACCOUNT_UUID + "] removed."); } GameplaySocialAssertions.assertAddFriendRequest( socialStub().lastAddFriendRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - Long.toString(SORA_ACCOUNT_ID)); + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); GameplaySocialAssertions.assertRemoveFriendRequest( socialStub().lastRemoveFriendRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - Long.toString(SORA_ACCOUNT_ID)); + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); } @Test @@ -378,14 +383,11 @@ void websocketFriendsRemoveByRosterOrdinalUsesRenderedRosterIdentity() throws Ex try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-remove-ordinal-conn")) { client.send("FRIENDS REMOVE #1"); - client.awaitContains("Sora [acct #" + SORA_ACCOUNT_ID + "] removed."); + client.awaitContains("Sora [acct #" + SORA_ACCOUNT_UUID + "] removed."); } GameplaySocialAssertions.assertRemoveFriendByOrdinalRequest( - socialStub().lastRemoveFriendByOrdinalRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - 1); + socialStub().lastRemoveFriendByOrdinalRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID, 1); } @Test @@ -396,16 +398,13 @@ void websocketFriendsShowUsesCanonicalFriendDetailSurface() throws Exception { try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "friends-show-detail-conn")) { client.send("FRIENDS SHOW #1"); - client.awaitContains("Friend Sora [acct #" + SORA_ACCOUNT_ID + "]"); + client.awaitContains("Friend Sora [acct #" + SORA_ACCOUNT_UUID + "]"); client.awaitContains("Presence: online in Demo World / Live Realm (idle)"); client.awaitContains("Roster entry: #1"); } GameplaySocialAssertions.assertGetFriendByOrdinalRequest( - socialStub().lastGetFriendByOrdinalRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), - 1); + socialStub().lastGetFriendByOrdinalRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID, 1); } @Test @@ -424,7 +423,7 @@ void websocketFriendsSummaryUsesCanonicalRosterSummarySurface() throws Exception } GameplaySocialAssertions.assertFriendRosterSummaryRequest( - socialStub().lastSummaryRequest(), Long.toString(TENANT_ID), Long.toString(ACCOUNT_ID)); + socialStub().lastSummaryRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); } @Test @@ -442,13 +441,11 @@ void websocketFriendsVisibilityShowsCurrentPolicy() throws Exception { } GameplaySocialAssertions.assertGetVisibilityRequest( - socialStub().lastGetVisibilityRequest(), - Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID)); + socialStub().lastGetVisibilityRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); GameplaySocialAssertions.assertUpdateVisibilityRequest( socialStub().lastUpdateVisibilityRequest(), Long.toString(TENANT_ID), - Long.toString(ACCOUNT_ID), + ACCOUNT_UUID, FriendPresenceVisibilityPolicy.FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); } @@ -641,7 +638,7 @@ private static synchronized void ensureTestServicesStarted() throws Exception { net.firedevops.firemud.socialgroups.v1.ListFriendPresenceResponse.newBuilder() .addPresences( FriendPresenceEntry.newBuilder() - .setFriendAccountId(Long.toString(SORA_ACCOUNT_ID)) + .setFriendAccountId(SORA_ACCOUNT_UUID) .setOnline(true) .setCharacterId(ChatTestFixtures.PLAYER_SORA) .setCharacterName("Sora") diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java index 4d5e11a1e6..310324f947 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java @@ -73,6 +73,7 @@ class GameSessionApplicationIntegrationTest { private static final String OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF = "6bf9e6d0-7f6b-4c85-b75e-d65949694f13"; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private static final String ACCOUNT_UUID = "5e1340f8-99c8-49fa-a4fe-5fc9d2075621"; private static final JwtUtil JWT_UTIL = new JwtUtil("testsecretkeytestsecretkeytest1234", 3600000L); @@ -349,7 +350,7 @@ void effectiveSettingsEndpointMergesScopedOverridesForPersistedSession() { new SessionContext( 999L, 42L, - "100", + ACCOUNT_UUID, "player@example.com", 55L, "Player", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java index dd852771f8..7233a33fb4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java @@ -60,6 +60,7 @@ DurableResumeTranscriptExpiryJob.class }) class GameSessionLoginIntegrationTest { + private static final String ACCOUNT_UUID = "00000000-0000-4000-8000-000000000007"; @LocalServerPort private int port; @MockitoBean private AccountClient accountClient; @@ -109,7 +110,10 @@ void setUp() { stubTransactionExecution(redisTemplate); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken("stub-token").setAccountId("7").build()); + AuthenticateResponse.newBuilder() + .setAuthToken("stub-token") + .setAccountId(ACCOUNT_UUID) + .build()); when(sharedSettingsAuthorityReader.readOverrides(anyLong(), org.mockito.ArgumentMatchers.any())) .thenReturn(ScopedSettingsSnapshot.empty()); when(commandService.enqueue(anyString(), anyString(), anyBoolean())) @@ -150,8 +154,9 @@ void loginCallsAccountServiceAndReturnsOk() throws Exception { } assertThat(payloads).anyMatch(s -> s.startsWith("OK LOGIN")); - assertThat(sessionContextService.findByTenantAndSessionId(42L, 1L)).isPresent(); - assertThat(redisValueStore).containsKey("accountrecentpresence:42:7"); + assertThat(sessionContextService.findByTenantAndSessionId(42L, 1L)) + .hasValueSatisfying(context -> assertThat(context.accountId()).isEqualTo(ACCOUNT_UUID)); + assertThat(redisValueStore).containsKey("accountrecentpresence:42:" + ACCOUNT_UUID); verify(accountClient).authenticate(eq("demo@example.com"), eq("swordfish")); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index e0f9bb5632..9c451a5bdf 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -119,6 +119,7 @@ @ActiveProfiles("test") @Import({NoGrpcServerTestConfiguration.class, InMemorySessionContextTestConfiguration.class}) class GameSessionWebSocketHandlerIntegrationTest { + private static final String ACCOUNT_UUID = "5e1340f8-99c8-49fa-a4fe-5fc9d2075621"; // Runtime target 2 belongs to the sandbox route in this fixture. private static final long CUTOVER_GAME_INSTANCE_ID = 3L; @@ -245,7 +246,7 @@ void setUp() { return members == null ? java.util.Set.of() : new java.util.LinkedHashSet<>(members); }); when(moderationPolicyClient.evaluateGameplayAdmission( - org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())) + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -262,11 +263,11 @@ void setUp() { .thenReturn( AuthenticateResponse.newBuilder() .setAuthToken("stub-token") - .setAccountId("123") + .setAccountId(ACCOUNT_UUID) .build()); org.mockito.Mockito.doReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_UUID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) @@ -296,7 +297,7 @@ void setUp() { net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("123") .setTenantId("22") - .setAccountId("123") + .setAccountId(ACCOUNT_UUID) .setName("Emberline") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setLevel(12) @@ -305,7 +306,7 @@ void setUp() { net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("456") .setTenantId("22") - .setAccountId("123") + .setAccountId(ACCOUNT_UUID) .setName("Sora") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setLevel(7) @@ -313,7 +314,10 @@ void setUp() { .build()) .when(entityManagementClient) .listCharactersByAccount( - eq("22"), eq("123"), eq("1"), eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + eq("22"), + eq(ACCOUNT_UUID), + eq("1"), + eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(commandService.enqueue( org.mockito.ArgumentMatchers.anyString(), eq("PLAY demo Emberline"), eq(false))) .thenReturn(CommandEnqueueResult.success()); @@ -657,8 +661,8 @@ void unexpectedDisconnectKeepsReplayEligibleForFreshReconnect() throws Exception GameplayAsyncAssertions.assertPresenceCountEventually( gameplayPresenceService, 22L, 1L, 0, java.time.Duration.ofSeconds(5)); assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)).isPresent(); - assertThat(accountRecentPresenceService.findByAccountIds(22L, List.of("123"))) - .containsKey("123"); + assertThat(accountRecentPresenceService.findByAccountIds(22L, List.of(ACCOUNT_UUID))) + .containsKey(ACCOUNT_UUID); List secondPayloads; try (GameplayWebSocketDriver client = openAdmittedGameplayDriver("42")) { @@ -825,7 +829,8 @@ void websocketLoginCanBrowseRealmsAndCharactersBeforePlay() throws Exception { verify(commandService, never()).enqueue("41", "REALMS demo", false); verify(commandService, never()).enqueue("41", "CHARS demo", false); verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", ACCOUNT_UUID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @Test @@ -900,7 +905,7 @@ void websocketActiveGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("789") .setTenantId("22") - .setAccountId("123") + .setAccountId(ACCOUNT_UUID) .setName("CutoverArrival") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setLevel(1) @@ -910,7 +915,7 @@ void websocketActiveGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() .when(entityManagementClient) .listCharactersByAccount( "22", - "123", + ACCOUNT_UUID, Long.toString(CUTOVER_GAME_INSTANCE_ID), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); @@ -943,7 +948,7 @@ void websocketActiveGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() org.mockito.Mockito.verify(entityManagementClient) .listCharactersByAccount( "22", - "123", + ACCOUNT_UUID, Long.toString(CUTOVER_GAME_INSTANCE_ID), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @@ -1002,7 +1007,7 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)) .hasValueSatisfying( context -> { - assertThat(context.accountId()).isEqualTo("123"); + assertThat(context.accountId()).isEqualTo(ACCOUNT_UUID); assertThat(context.gameInstanceId()).isZero(); assertThat(context.characterId()).isZero(); assertThat(context.bootstrapGameInstanceId()).isEqualTo(2L); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java index 155d484a7b..887eb3a632 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java @@ -40,6 +40,7 @@ import org.mockito.ArgumentCaptor; class AccountClientTest { + private static final String ACCOUNT_UUID = "00000000-0000-4000-8000-000000000042"; @Test void authenticateReturnsUnavailableWhenStubIsNotInitialized() throws Exception { @@ -200,6 +201,103 @@ void emailLoginChallengeRequestHasNoTenantScopeField() throws Exception { .isNull(); } + @ParameterizedTest + @ValueSource( + strings = { + "42", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000000A", + " 00000000-0000-4000-8000-000000000042" + }) + void runtimeReadersRejectNonCanonicalAccountsBeforeCallingAccount(String invalidAccount) + throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + AccountClient client = newClient(stub); + assertThat( + client + .getTenantMembershipForRuntime(invalidAccount, "7", "request-1") + .getError() + .getCode()) + .isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); + assertThat( + client + .getRealmAccessGrantForRuntime(invalidAccount, "7", "world", "realm", "request-1") + .getError() + .getCode()) + .isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); + org.mockito.Mockito.verifyNoInteractions(stub); + } + + @ParameterizedTest + @ValueSource( + strings = { + "42", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-000000000043" + }) + void runtimeMembershipRejectsUncorrelatedAccountResult(String returnedAccount) throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.getTenantMembershipForRuntime(any(GetTenantMembershipForRuntimeRequest.class))) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId(returnedAccount) + .setTenantId("7") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(true) + .build()); + AccountClient client = newClient(stub); + assertThat( + client + .getTenantMembershipForRuntime(ACCOUNT_UUID, "7", "request-1") + .getError() + .getCode()) + .isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); + verify(stub, times(1)) + .getTenantMembershipForRuntime(any(GetTenantMembershipForRuntimeRequest.class)); + } + + @Test + void realmGrantRequiresExactAccountTenantWorldAndRealmResult() throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + var exact = + GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("7") + .setWorldSlug("world") + .setRealmSlug("realm") + .setGranted(true) + .setGrantVersion(4L) + .build(); + AccountClient client = newClient(stub); + for (var result : + java.util.List.of( + exact.toBuilder().setAccountId("42").build(), + exact.toBuilder().setAccountId("00000000-0000-4000-8000-000000000043").build(), + exact.toBuilder().setTenantId("8").build(), + exact.toBuilder().setWorldSlug("other").build(), + exact.toBuilder().setRealmSlug("other").build())) { + when(stub.getRealmAccessGrantForRuntime(any(GetRealmAccessGrantForRuntimeRequest.class))) + .thenReturn(result); + assertThat( + client + .getRealmAccessGrantForRuntime(ACCOUNT_UUID, "7", "world", "realm", "request-1") + .getError() + .getCode()) + .isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); + } + when(stub.getRealmAccessGrantForRuntime(any(GetRealmAccessGrantForRuntimeRequest.class))) + .thenReturn(exact); + assertThat( + client.getRealmAccessGrantForRuntime(ACCOUNT_UUID, "7", "world", "realm", "request-1")) + .isEqualTo(exact); + } + @Test void runtimeMembershipCallerUsesCanonicalAccountTenantRequest() throws Exception { AccountServiceGrpc.AccountServiceBlockingStub stub = @@ -207,7 +305,7 @@ void runtimeMembershipCallerUsesCanonicalAccountTenantRequest() throws Exception when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); GetTenantMembershipForRuntimeResponse expected = GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("42") + .setAccountId(ACCOUNT_UUID) .setTenantId("7") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) @@ -219,12 +317,12 @@ void runtimeMembershipCallerUsesCanonicalAccountTenantRequest() throws Exception AccountClient client = newClient(stub); GetTenantMembershipForRuntimeResponse actual = - client.getTenantMembershipForRuntime("42", "7", null); + client.getTenantMembershipForRuntime(ACCOUNT_UUID, "7", null); ArgumentCaptor captor = ArgumentCaptor.forClass(GetTenantMembershipForRuntimeRequest.class); verify(stub).getTenantMembershipForRuntime(captor.capture()); - assertThat(captor.getValue().getAccountId()).isEqualTo("42"); + assertThat(captor.getValue().getAccountId()).isEqualTo(ACCOUNT_UUID); assertThat(captor.getValue().getTenantId()).isEqualTo("7"); assertThat(captor.getValue().getRequestId()).isEmpty(); assertThat(actual).isEqualTo(expected); @@ -233,7 +331,7 @@ void runtimeMembershipCallerUsesCanonicalAccountTenantRequest() throws Exception @Test void runtimeMembershipReturnsCanonicalUnavailableWhenStubIsMissing() throws Exception { GetTenantMembershipForRuntimeResponse response = - newClient(null).getTenantMembershipForRuntime("42", "7", "request-1"); + newClient(null).getTenantMembershipForRuntime(ACCOUNT_UUID, "7", "request-1"); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Membership authority unavailable"); @@ -242,7 +340,8 @@ void runtimeMembershipReturnsCanonicalUnavailableWhenStubIsMissing() throws Exce @Test void realmAccessGrantReturnsCanonicalUnavailableWhenStubIsMissing() throws Exception { GetRealmAccessGrantForRuntimeResponse response = - newClient(null).getRealmAccessGrantForRuntime("42", "7", "world", "realm", "request-1"); + newClient(null) + .getRealmAccessGrantForRuntime(ACCOUNT_UUID, "7", "world", "realm", "request-1"); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Realm grant authority unavailable"); @@ -257,7 +356,7 @@ void runtimeMembershipRetriesOnceAfterUnavailableAndPreservesSuccess() throws Ex .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); GetTenantMembershipForRuntimeResponse expected = GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("42") + .setAccountId(ACCOUNT_UUID) .setTenantId("7") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) @@ -269,7 +368,7 @@ void runtimeMembershipRetriesOnceAfterUnavailableAndPreservesSuccess() throws Ex .thenReturn(expected); GetTenantMembershipForRuntimeResponse actual = - fixture.client().getTenantMembershipForRuntime("42", "7", "request-1"); + fixture.client().getTenantMembershipForRuntime(ACCOUNT_UUID, "7", "request-1"); assertThat(actual).isEqualTo(expected); verify(fixture.initialStub()) @@ -292,7 +391,7 @@ void runtimeMembershipNormalizesExhaustedUnavailableToCanonicalUnavailable() thr .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); GetTenantMembershipForRuntimeResponse response = - fixture.client().getTenantMembershipForRuntime("42", "7", "request-1"); + fixture.client().getTenantMembershipForRuntime(ACCOUNT_UUID, "7", "request-1"); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Membership authority unavailable"); @@ -349,7 +448,9 @@ void realmAccessGrantNormalizesExhaustedUnavailableToCanonicalUnavailable() thro .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); GetRealmAccessGrantForRuntimeResponse response = - fixture.client().getRealmAccessGrantForRuntime("42", "7", "world", "realm", "request-1"); + fixture + .client() + .getRealmAccessGrantForRuntime(ACCOUNT_UUID, "7", "world", "realm", "request-1"); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Realm grant authority unavailable"); @@ -371,7 +472,7 @@ void runtimeMembershipNormalizesInitialInternalWithoutRetryOrChannelRebuild() th AccountClient client = newClient(stub, channelFactory); GetTenantMembershipForRuntimeResponse response = - client.getTenantMembershipForRuntime("42", "7", "request-1"); + client.getTenantMembershipForRuntime(ACCOUNT_UUID, "7", "request-1"); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Membership authority unavailable"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java index dd50ee2bde..18f270a448 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java @@ -11,13 +11,45 @@ import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.service.SessionContext; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; class EntityManagementClientTest { private static final SessionContext SESSION_CONTEXT = new SessionContext( - 41L, 22L, "20", "", 123L, "", 1L, "R-1021", "", null, 1L, "world", "realm", 17L, + 41L, + 22L, + "00000000-0000-4000-8000-000000000020", + "", + 123L, + "", + 1L, + "R-1021", + "", + null, + 1L, + "world", + "realm", + 17L, "SHARED"); + @ParameterizedTest + @ValueSource( + strings = { + "20", + "not-an-account", + "00000000-0000-0000-0000-000000000000", + " 00000000-0000-4000-8000-000000000020" + }) + void rosterReadRejectsNonCanonicalAccountBeforeTransport(String accountId) { + EntityManagementClient client = newClient(); + assertThatThrownBy( + () -> + client.listCharactersByAccount( + "22", accountId, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void listRoomEntitiesFailsClosedWhenSessionContextDropsPartOfAdmittedRoutingBundle() { EntityManagementClient client = newClient(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java index 1effab5ef4..7182cd6e7d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -43,9 +44,24 @@ import org.mockito.ArgumentCaptor; class GameLogicClientTest { + private static final String ACCOUNT_UUID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; private static final SessionContext SESSION_CONTEXT = new SessionContext( - 41L, 22L, "0", "", 123L, "", 1L, "R-1021", "", null, 1L, "world", "realm", 17L, "SHARED"); + 41L, + 22L, + ACCOUNT_UUID, + "", + 123L, + "", + 1L, + "R-1021", + "", + null, + 1L, + "world", + "realm", + 17L, + "SHARED"); @Test void resolveLookForwardsGameInstanceIdIntoRoomInstance() throws Exception { @@ -345,7 +361,7 @@ void pickupVisibleRoomItemForwardsRawReferenceAndSessionContextThroughGameLogic( PickupVisibleRoomItemRequest.newBuilder() .setTenantId("22") .setSessionId("41") - .setAccountId("0") + .setAccountId(ACCOUNT_UUID) .setCharacterId("123") .setGameInstanceId("1") .setRoomInstanceId("R-1021") @@ -369,7 +385,7 @@ void pickupVisibleRoomItemForwardsRawReferenceAndSessionContextThroughGameLogic( } @Test - void sendCommunicationMapsNullAccountToEmptyAndPreservesOpaqueAccount() throws Exception { + void sendCommunicationForwardsCanonicalAccountUuidUnchanged() throws Exception { GameLogicClient client = newClient(); GameLogicServiceGrpc.GameLogicServiceBlockingStub stub = mock(GameLogicServiceGrpc.GameLogicServiceBlockingStub.class); @@ -379,7 +395,7 @@ void sendCommunicationMapsNullAccountToEmptyAndPreservesOpaqueAccount() throws E setStub(client, stub); client.sendCommunication( - sessionContextWithAccountId(null), + sessionContextWithAccountId(ACCOUNT_UUID), "Sora", "R-1021", CommunicationType.SAY, @@ -387,22 +403,47 @@ void sendCommunicationMapsNullAccountToEmptyAndPreservesOpaqueAccount() throws E null, null, null); - client.sendCommunication( - sessionContextWithAccountId("acct:opaque/legacy"), - "Sora", - "R-1021", - CommunicationType.SAY, - "hello", - null, - null, - null); - ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(SendCommunicationRequest.class); - verify(stub, times(2)).sendCommunication(requestCaptor.capture()); - assertThat(requestCaptor.getAllValues()) - .extracting(SendCommunicationRequest::getAccountId) - .containsExactly("", "acct:opaque/legacy"); + verify(stub).sendCommunication(requestCaptor.capture()); + assertThat(requestCaptor.getValue().getAccountId()).isEqualTo(ACCOUNT_UUID); + } + + @Test + void sendCommunicationRejectsInvalidAccountUuidBeforeRpc() throws Exception { + GameLogicClient client = newClient(); + GameLogicServiceGrpc.GameLogicServiceBlockingStub stub = + mock(GameLogicServiceGrpc.GameLogicServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + setStub(client, stub); + + for (String accountId : + new String[] { + null, + "", + "42", + "00000000-0000-0000-0000-000000000000", + ACCOUNT_UUID.toUpperCase(java.util.Locale.ROOT), + " " + ACCOUNT_UUID + " ", + " ", + "not-a-uuid" + }) { + assertThatThrownBy( + () -> + client.sendCommunication( + sessionContextWithAccountId(accountId), + "Sora", + "R-1021", + CommunicationType.SAY, + "hello", + null, + null, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical non-nil Account UUID"); + } + + verify(stub, never()).sendCommunication(any(SendCommunicationRequest.class)); } @Test @@ -487,7 +528,7 @@ void dropCarriedItemForwardsRawReferenceAndSessionContextThroughGameLogic() thro DropCarriedItemRequest.newBuilder() .setTenantId("22") .setSessionId("41") - .setAccountId("0") + .setAccountId(ACCOUNT_UUID) .setCharacterId("123") .setGameInstanceId("1") .setRoomInstanceId("R-1021") @@ -634,7 +675,7 @@ private static GameLogicClient newClient() { GameplaySessionAttestationService attestationService = mock(GameplaySessionAttestationService.class); when(attestationService.issueGameplaySessionAttestation( - "22", "41", "0", "123", "1", "R-1021", "world", "realm", "17", "SHARED")) + "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "world", "realm", "17", "SHARED")) .thenReturn("attestation"); when(attestationService.issueGameplaySessionAttestation( "22", "41", null, "123", "1", "R-1021", "world", "realm", "17", "SHARED")) @@ -652,7 +693,7 @@ private static GameLogicClient newClient() { "SHARED")) .thenReturn("attestation"); when(attestationService.issueGameplaySessionAttestation( - "22", "41", "0", "123", "1", "R-2045", "world", "realm", "17", "SHARED")) + "22", "41", ACCOUNT_UUID, "123", "1", "R-2045", "world", "realm", "17", "SHARED")) .thenReturn("destination-attestation"); return new GameLogicClient( new ServiceEndpointsProperties(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java index 7b7d5aa4b8..482c33be33 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java @@ -39,11 +39,15 @@ class FriendsCommandHandlerTest { private record InvalidAccountAction(List args, String errorCode, String message) {} + private static final String CALLER_ACCOUNT_ID = "a0000000-0000-4000-8000-000000000041"; + private static final String FRIEND_ACCOUNT_ID = "b0000000-0000-4000-8000-000000000077"; + private static final String OTHER_FRIEND_ACCOUNT_ID = "c0000000-0000-4000-8000-000000000088"; + private static final SessionContext GAMEPLAY_CONTEXT = new SessionContext( 7L, 1L, - "41", + CALLER_ACCOUNT_ID, "demo@example.com", 99L, "Emberline", @@ -118,7 +122,16 @@ void unsupportedAccountIdsFailByActionBeforeEntitySocialOrEventCalls() { "FRIEND_VISIBILITY_UPDATE_UNAVAILABLE", "Friend presence visibility update unavailable")); - for (String accountId : List.of("opaque-account-uuid", "", "0", "-41")) { + for (String accountId : + List.of( + "opaque-account-uuid", + "", + "0", + "-41", + "41", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000007-", + CALLER_ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT))) { SessionContext context = gameplayContextWithAccountId(accountId); for (InvalidAccountAction action : actions) { TextCommandInterpretationResult result = @@ -173,22 +186,22 @@ void usageErrorsRemainVisibleBeforeUnsupportedAccountFailure() { } @Test - void friendsListPreservesMaximumPositiveLongAccountId() { + void friendsListPassesCanonicalAccountUuidUnchanged() { SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); FriendsCommandHandler handler = newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); - when(socialGroupsClient.listFriends(1L, Long.MAX_VALUE)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn(ListFriendsResponse.newBuilder().build()); TextCommandInterpretationResult result = handler.handle( new TextCommand(TextCommandType.FRIENDS, List.of(), "FRIENDS"), - gameplayContextWithAccountId(Long.toString(Long.MAX_VALUE))); + gameplayContextWithAccountId(CALLER_ACCOUNT_ID)); assertThat(result.commandResult().accepted()).isTrue(); - Mockito.verify(socialGroupsClient).listFriends(1L, Long.MAX_VALUE); + Mockito.verify(socialGroupsClient).listFriends(1L, CALLER_ACCOUNT_ID); Mockito.verify(scriptEventPublisher).publishCommandEvent(Mockito.any(), Mockito.any()); } @@ -199,16 +212,16 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); FriendsCommandHandler handler = newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( FriendRosterEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterId("99") .setCharacterName("Sora") @@ -243,7 +256,7 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { .satisfies( entry -> { assertThat(entry.friendLinkId()).isNull(); - assertThat(entry.friendAccountId()).isEqualTo(77L); + assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(entry.status()).isEqualTo("active"); assertThat(entry.linkedAtEpochMs()).isNull(); assertThat(entry.displayName()).isEqualTo("Sora"); @@ -253,7 +266,8 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) - .contains("Sora [acct #77] - online in Demo World / Live Realm (idle)"); + .contains( + "Sora [acct #" + FRIEND_ACCOUNT_ID + "] - online in Demo World / Live Realm (idle)"); Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.any(), @@ -272,16 +286,16 @@ void friendsFallsBackToBoundedOfflineLabelWhenDetailsAreSuppressed() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( FriendRosterEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(false) .setLastSeenAtMs( Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()) @@ -306,7 +320,7 @@ void friendsFallsBackToBoundedOfflineLabelWhenDetailsAreSuppressed() { entry -> { assertThat(entry.friendLinkId()).isNull(); assertThat(entry.status()).isEqualTo("active"); - assertThat(entry.displayName()).isEqualTo("Friend #77"); + assertThat(entry.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID); assertThat(entry.lastSeenAtEpochMs()) .isEqualTo(Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()); assertThat(entry.recentDisposition()).isEqualTo("LOGOUT"); @@ -320,13 +334,15 @@ void friendsAddLinksAccountScopedFriendAndReturnsNotice() { ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); FriendsCommandHandler handler = newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); - when(socialGroupsClient.addFriend(1L, 41L, 77L)) + when(socialGroupsClient.addFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn(AddFriendResponse.newBuilder().setSuccess(true).build()); TextCommandInterpretationResult result = handler.handle( new TextCommand( - TextCommandType.FRIENDS, java.util.List.of("ADD", "77"), "friends add 77"), + TextCommandType.FRIENDS, + java.util.List.of("ADD", FRIEND_ACCOUNT_ID), + "FRIENDS ADD " + FRIEND_ACCOUNT_ID), GAMEPLAY_CONTEXT); assertThat(result.commandResult().accepted()).isTrue(); @@ -334,12 +350,12 @@ void friendsAddLinksAccountScopedFriendAndReturnsNotice() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Friend #77 added."); + assertThat(output.text()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + " added."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("ADD"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); - assertThat(mutation.displayName()).isEqualTo("Friend #77"); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); + assertThat(mutation.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID); assertThat(mutation.characterName()).isNull(); assertThat(mutation.ordinal()).isNull(); }); @@ -349,7 +365,8 @@ void friendsAddLinksAccountScopedFriendAndReturnsNotice() { Mockito.argThat( gameplayCommand -> "FRIENDS".equals(gameplayCommand.getCommandName()) - && "friends add 77".equals(gameplayCommand.getCommandText()))); + && ("FRIENDS ADD " + FRIEND_ACCOUNT_ID) + .equals(gameplayCommand.getCommandText()))); } @Test @@ -359,7 +376,8 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE)) + when(socialGroupsClient.listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE) @@ -368,10 +386,10 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { .addFriends( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterName("Sora") .build()) @@ -396,9 +414,9 @@ void friendsOnlineFiltersCanonicalRosterWithoutRenumbering() { new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) .contains("Friends ONLINE [1/2]:") - .contains("1) Sora [acct #77] - online"); + .contains("1) Sora [acct #" + FRIEND_ACCOUNT_ID + "] - online"); Mockito.verify(socialGroupsClient) - .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); + .listFriends(1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); } @Test @@ -408,7 +426,8 @@ void friendsPrivateFiltersCanonicalRosterByVisibilityPolicy() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE)) + when(socialGroupsClient.listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE) @@ -417,10 +436,10 @@ void friendsPrivateFiltersCanonicalRosterByVisibilityPolicy() { .addFriends( FriendRosterEntry.newBuilder() .setOrdinal(2) - .setFriendAccountId("88") + .setFriendAccountId(OTHER_FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("88") + .setFriendAccountId(OTHER_FRIEND_ACCOUNT_ID) .setOnline(false) .setVisibilityPolicy( net.firedevops.firemud.socialgroups.v1 @@ -446,7 +465,7 @@ void friendsPrivateFiltersCanonicalRosterByVisibilityPolicy() { .satisfies( entry -> { assertThat(entry.ordinal()).isEqualTo(2); - assertThat(entry.friendAccountId()).isEqualTo(88L); + assertThat(entry.friendAccountId()).isEqualTo(OTHER_FRIEND_ACCOUNT_ID); assertThat(entry.visibilityPolicy()).isEqualTo("PRIVATE"); }); assertThat( @@ -455,7 +474,7 @@ void friendsPrivateFiltersCanonicalRosterByVisibilityPolicy() { .render(result.outputs().getFirst())) .contains("Friends PRIVATE [1/2]:"); Mockito.verify(socialGroupsClient) - .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE); + .listFriends(1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_PRIVATE); } @Test @@ -465,7 +484,8 @@ void friendsSharedFiltersCanonicalRosterByPlayableStateScope() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED)) + when(socialGroupsClient.listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED) @@ -474,10 +494,10 @@ void friendsSharedFiltersCanonicalRosterByPlayableStateScope() { .addFriends( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterName("Sora") .setPlayableStateScope( @@ -501,7 +521,7 @@ void friendsSharedFiltersCanonicalRosterByPlayableStateScope() { .satisfies( entry -> { assertThat(entry.ordinal()).isEqualTo(1); - assertThat(entry.friendAccountId()).isEqualTo(77L); + assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(entry.playableStateScope()).isEqualTo("SHARED"); }); assertThat( @@ -510,7 +530,7 @@ void friendsSharedFiltersCanonicalRosterByPlayableStateScope() { .render(result.outputs().getFirst())) .contains("Friends SHARED [1/2]:"); Mockito.verify(socialGroupsClient) - .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED); + .listFriends(1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED); } @Test @@ -520,7 +540,8 @@ void friendsRecentFiltersOfflineEntriesWithRecentPresence() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_RECENT)) + when(socialGroupsClient.listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_RECENT)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_RECENT) @@ -529,10 +550,10 @@ void friendsRecentFiltersOfflineEntriesWithRecentPresence() { .addFriends( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(false) .setLastSeenAtMs( Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()) @@ -552,7 +573,7 @@ void friendsRecentFiltersOfflineEntriesWithRecentPresence() { assertThat(view.matchCount()).isEqualTo(1); assertThat(view.friends()) .singleElement() - .satisfies(entry -> assertThat(entry.friendAccountId()).isEqualTo(77L)); + .satisfies(entry -> assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID)); } @Test @@ -562,7 +583,7 @@ void friendsSummaryUsesCanonicalRosterSummarySurface() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriendRosterSummary(1L, 41L)) + when(socialGroupsClient.getFriendRosterSummary(1L, CALLER_ACCOUNT_ID)) .thenReturn( GetFriendRosterSummaryResponse.newBuilder() .setSummary( @@ -621,7 +642,7 @@ void friendsSummaryUsesCanonicalRosterSummarySurface() { .contains("Visibility private: 1") .contains("Scope shared: 2") .contains("Scope isolated: 1"); - Mockito.verify(socialGroupsClient).getFriendRosterSummary(1L, 41L); + Mockito.verify(socialGroupsClient).getFriendRosterSummary(1L, CALLER_ACCOUNT_ID); } @Test @@ -637,8 +658,12 @@ void friendsAddResolvesCharacterNameToCanonicalAccountId() { Mockito.eq("Sora"))) .thenReturn( Optional.of( - Character.newBuilder().setId("99").setAccountId("77").setName("Sora").build())); - when(socialGroupsClient.addFriend(1L, 41L, 77L)) + Character.newBuilder() + .setId("99") + .setAccountId(FRIEND_ACCOUNT_ID) + .setName("Sora") + .build())); + when(socialGroupsClient.addFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn(AddFriendResponse.newBuilder().setSuccess(true).build()); TextCommandInterpretationResult result = @@ -652,15 +677,15 @@ void friendsAddResolvesCharacterNameToCanonicalAccountId() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Sora [acct #77] added."); + assertThat(output.text()).isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] added."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("ADD"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(mutation.displayName()).isEqualTo("Sora"); assertThat(mutation.characterName()).isEqualTo("Sora"); }); - Mockito.verify(socialGroupsClient).addFriend(1L, 41L, 77L); + Mockito.verify(socialGroupsClient).addFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID); } @Test @@ -670,13 +695,15 @@ void friendsRemoveUnlinksAccountScopedFriendAndReturnsNotice() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.removeFriend(1L, 41L, 77L)) + when(socialGroupsClient.removeFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn(RemoveFriendResponse.newBuilder().setSuccess(true).build()); TextCommandInterpretationResult result = handler.handle( new TextCommand( - TextCommandType.FRIENDS, java.util.List.of("REMOVE", "77"), "FRIENDS REMOVE 77"), + TextCommandType.FRIENDS, + java.util.List.of("REMOVE", FRIEND_ACCOUNT_ID), + "FRIENDS REMOVE " + FRIEND_ACCOUNT_ID), GAMEPLAY_CONTEXT); assertThat(result.commandResult().accepted()).isTrue(); @@ -684,12 +711,12 @@ void friendsRemoveUnlinksAccountScopedFriendAndReturnsNotice() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Friend #77 removed."); + assertThat(output.text()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + " removed."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("REMOVE"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); - assertThat(mutation.displayName()).isEqualTo("Friend #77"); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); + assertThat(mutation.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID); assertThat(mutation.characterName()).isNull(); assertThat(mutation.ordinal()).isNull(); }); @@ -708,8 +735,12 @@ void friendsRemoveResolvesCharacterNameToCanonicalAccountId() { Mockito.eq("Sora"))) .thenReturn( Optional.of( - Character.newBuilder().setId("99").setAccountId("77").setName("Sora").build())); - when(socialGroupsClient.removeFriend(1L, 41L, 77L)) + Character.newBuilder() + .setId("99") + .setAccountId(FRIEND_ACCOUNT_ID) + .setName("Sora") + .build())); + when(socialGroupsClient.removeFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn(RemoveFriendResponse.newBuilder().setSuccess(true).build()); TextCommandInterpretationResult result = @@ -725,15 +756,16 @@ void friendsRemoveResolvesCharacterNameToCanonicalAccountId() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Sora [acct #77] removed."); + assertThat(output.text()) + .isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] removed."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("REMOVE"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(mutation.displayName()).isEqualTo("Sora"); assertThat(mutation.characterName()).isEqualTo("Sora"); }); - Mockito.verify(socialGroupsClient).removeFriend(1L, 41L, 77L); + Mockito.verify(socialGroupsClient).removeFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID); } @Test @@ -743,17 +775,17 @@ void friendsRemoveByOrdinalUsesCanonicalRemoveSurface() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.removeFriendByOrdinal(1L, 41L, 1)) + when(socialGroupsClient.removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1)) .thenReturn( RemoveFriendByOrdinalResponse.newBuilder() .setSuccess(true) .setRemovedFriend( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setCharacterName("Sora") .build()) .build()) @@ -770,16 +802,17 @@ void friendsRemoveByOrdinalUsesCanonicalRemoveSurface() { .singleElement() .satisfies( output -> { - assertThat(output.text()).isEqualTo("Sora [acct #77] removed."); + assertThat(output.text()) + .isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] removed."); assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); assertThat(mutation.action()).isEqualTo("REMOVE"); - assertThat(mutation.friendAccountId()).isEqualTo(77L); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(mutation.displayName()).isEqualTo("Sora"); assertThat(mutation.characterName()).isEqualTo("Sora"); assertThat(mutation.ordinal()).isEqualTo(1); }); - Mockito.verify(socialGroupsClient).removeFriendByOrdinal(1L, 41L, 1); + Mockito.verify(socialGroupsClient).removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1); } @Test @@ -789,7 +822,7 @@ void friendsRemoveByOrdinalRejectsMalformedReturnedFriendAccountId() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.removeFriendByOrdinal(1L, 41L, 1)) + when(socialGroupsClient.removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1)) .thenReturn( RemoveFriendByOrdinalResponse.newBuilder() .setSuccess(true) @@ -823,18 +856,18 @@ void friendsShowReturnsCanonicalFriendDetailView() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriend(1L, 41L, 77L)) + when(socialGroupsClient.getFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID)) .thenReturn( GetFriendResponse.newBuilder() .setFriend( FriendRosterEntry.newBuilder() .setFriendLinkId("11") - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setCreatedAtMs(Instant.parse("2026-04-10T01:02:03Z").toEpochMilli()) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setOnline(true) .setCharacterName("Sora") .setWorldDisplayName("Demo World") @@ -852,7 +885,9 @@ void friendsShowReturnsCanonicalFriendDetailView() { TextCommandInterpretationResult result = handler.handle( new TextCommand( - TextCommandType.FRIENDS, java.util.List.of("SHOW", "77"), "FRIENDS SHOW 77"), + TextCommandType.FRIENDS, + java.util.List.of("SHOW", FRIEND_ACCOUNT_ID), + "FRIENDS SHOW " + FRIEND_ACCOUNT_ID), GAMEPLAY_CONTEXT); assertThat(result.commandResult().accepted()).isTrue(); @@ -861,7 +896,7 @@ void friendsShowReturnsCanonicalFriendDetailView() { .extracting(PlayerOutput::payload) .isInstanceOf(FriendDetailViewOutput.class); FriendDetailViewOutput detail = (FriendDetailViewOutput) result.outputs().getFirst().payload(); - assertThat(detail.friend().friendAccountId()).isEqualTo(77L); + assertThat(detail.friend().friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); assertThat(detail.friend().friendLinkId()).isEqualTo(11L); assertThat(detail.friend().characterName()).isEqualTo("Sora"); assertThat(detail.friend().playableStateScope()).isEqualTo("SHARED"); @@ -870,7 +905,7 @@ void friendsShowReturnsCanonicalFriendDetailView() { new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) .render(result.outputs().getFirst())) - .contains("Friend Sora [acct #77]") + .contains("Friend Sora [acct #" + FRIEND_ACCOUNT_ID + "]") .contains("Presence: online in Demo World / Live Realm (idle)") .contains("State scope: shared") .contains("Pointer version: 17"); @@ -883,16 +918,16 @@ void friendsShowByOrdinalUsesCanonicalDetailSurface() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriendByOrdinal(1L, 41L, 1)) + when(socialGroupsClient.getFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1)) .thenReturn( GetFriendByOrdinalResponse.newBuilder() .setFriend( FriendRosterEntry.newBuilder() .setOrdinal(1) - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setPresence( FriendPresenceEntry.newBuilder() - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setCharacterName("Sora") .build()) .build()) @@ -907,39 +942,72 @@ void friendsShowByOrdinalUsesCanonicalDetailSurface() { assertThat(result.commandResult().accepted()).isTrue(); FriendDetailViewOutput detail = (FriendDetailViewOutput) result.outputs().getFirst().payload(); assertThat(detail.friend().ordinal()).isEqualTo(1); - Mockito.verify(socialGroupsClient).getFriendByOrdinal(1L, 41L, 1); + Mockito.verify(socialGroupsClient).getFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1); } @Test - void friendsAddAndRemoveRejectSelfLinkForEquivalentNumericAccountText() { + void friendsAddAndRemoveRejectSelfLinkByCanonicalUuid() { SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); FriendsCommandHandler handler = newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); - for (String accountIdText : List.of("41", "041", "+41")) { - SessionContext context = gameplayContextWithAccountId(accountIdText); - for (String action : List.of("ADD", "REMOVE")) { - TextCommandInterpretationResult result = - handler.handle( - new TextCommand( - TextCommandType.FRIENDS, List.of(action, "41"), "FRIENDS " + action + " 41"), - context); - - assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("FRIEND_SELF_LINK_FORBIDDEN"); - assertThat(result.outputs()) - .singleElement() - .extracting(PlayerOutput::text) - .isEqualTo( - "ERROR FRIEND_SELF_LINK_FORBIDDEN Cannot add or remove your own account as a friend"); - } + for (String action : List.of("ADD", "REMOVE")) { + TextCommandInterpretationResult result = + handler.handle( + new TextCommand( + TextCommandType.FRIENDS, + List.of(action, CALLER_ACCOUNT_ID), + "FRIENDS " + action + " " + CALLER_ACCOUNT_ID), + GAMEPLAY_CONTEXT); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("FRIEND_SELF_LINK_FORBIDDEN"); + assertThat(result.outputs()) + .singleElement() + .extracting(PlayerOutput::text) + .isEqualTo( + "ERROR FRIEND_SELF_LINK_FORBIDDEN Cannot add or remove your own account as a friend"); } Mockito.verifyNoInteractions(socialGroupsClient, entityManagementClient, scriptEventPublisher); } + @Test + void friendsMutationsRejectLegacyNumericAccountIdsWithoutResolvingThemAsNames() { + SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); + EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); + FriendsCommandHandler handler = + newHandler( + socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); + + for (String legacyId : + List.of( + "77", + "+77", + "00077", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000007-", + FRIEND_ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT))) { + TextCommandInterpretationResult result = + handler.handle( + new TextCommand( + TextCommandType.FRIENDS, List.of("ADD", legacyId), "FRIENDS ADD " + legacyId), + GAMEPLAY_CONTEXT); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.outputs()) + .singleElement() + .extracting(PlayerOutput::text) + .isEqualTo( + "ERROR INVALID_ARGUMENT Friend account ID must be a canonical non-nil UUID or a character name"); + } + + Mockito.verifyNoInteractions(socialGroupsClient, entityManagementClient); + } + @Test void friendsMutationRejectsMissingTarget() { SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); @@ -968,7 +1036,7 @@ void friendsRemoveRejectsUnknownRosterOrdinal() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.removeFriendByOrdinal(1L, 41L, 1)) + when(socialGroupsClient.removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1)) .thenReturn( RemoveFriendByOrdinalResponse.newBuilder() .setSuccess(false) @@ -1058,16 +1126,18 @@ void friendsListTreatsMalformedFriendLinkIdAsAbsent() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L)) + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) .thenReturn( ListFriendsResponse.newBuilder() .addFriends( FriendRosterEntry.newBuilder() .setFriendLinkId("abc") - .setFriendAccountId("77") + .setFriendAccountId(FRIEND_ACCOUNT_ID) .setStatus("active") .setPresence( - FriendPresenceEntry.newBuilder().setFriendAccountId("77").build()) + FriendPresenceEntry.newBuilder() + .setFriendAccountId(FRIEND_ACCOUNT_ID) + .build()) .build()) .build()); @@ -1085,32 +1155,42 @@ void friendsListTreatsMalformedFriendLinkIdAsAbsent() { } @Test - void friendsListRejectsMalformedFriendAccountIdPayload() { + void friendsListRejectsLegacyNilAndMalformedFriendAccountIdPayloads() { SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.listFriends(1L, 41L)) - .thenReturn( - ListFriendsResponse.newBuilder() - .addFriends( - FriendRosterEntry.newBuilder() - .setFriendAccountId("abc") - .setStatus("active") - .setPresence( - FriendPresenceEntry.newBuilder().setFriendAccountId("abc").build()) - .build()) - .build()); - - TextCommandInterpretationResult result = - handler.handle( - new TextCommand(TextCommandType.FRIENDS, java.util.List.of(), "FRIENDS"), - GAMEPLAY_CONTEXT); - - assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("FRIEND_PRESENCE_UNAVAILABLE"); - assertThat(result.commandResult().errorMessage()).isEqualTo("Friend presence unavailable"); + for (String invalidAccountId : + List.of( + "abc", + "77", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000007-", + FRIEND_ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT))) { + when(socialGroupsClient.listFriends(1L, CALLER_ACCOUNT_ID)) + .thenReturn( + ListFriendsResponse.newBuilder() + .addFriends( + FriendRosterEntry.newBuilder() + .setFriendAccountId(invalidAccountId) + .setStatus("active") + .setPresence( + FriendPresenceEntry.newBuilder() + .setFriendAccountId(invalidAccountId) + .build()) + .build()) + .build()); + + TextCommandInterpretationResult result = + handler.handle( + new TextCommand(TextCommandType.FRIENDS, java.util.List.of(), "FRIENDS"), + GAMEPLAY_CONTEXT); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("FRIEND_PRESENCE_UNAVAILABLE"); + assertThat(result.commandResult().errorMessage()).isEqualTo("Friend presence unavailable"); + } } @Test @@ -1120,7 +1200,7 @@ void friendsVisibilityShowsCurrentCanonicalPolicy() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriendPresencePolicy(1L, 41L)) + when(socialGroupsClient.getFriendPresencePolicy(1L, CALLER_ACCOUNT_ID)) .thenReturn( GetFriendPresencePolicyResponse.newBuilder() .setCurrentPolicy( @@ -1155,7 +1235,7 @@ void friendsVisibilityShowsCurrentCanonicalPolicy() { .render(result.outputs().getFirst())) .contains("Friend presence visibility: FRIENDS_ONLY") .contains("Use FRIENDS VISIBILITY ."); - Mockito.verify(socialGroupsClient).getFriendPresencePolicy(1L, 41L); + Mockito.verify(socialGroupsClient).getFriendPresencePolicy(1L, CALLER_ACCOUNT_ID); } @Test @@ -1165,7 +1245,7 @@ void friendsVisibilityViewFailsClosedWhenCanonicalPolicyReadIsUnavailable() { FriendsCommandHandler handler = newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - when(socialGroupsClient.getFriendPresencePolicy(1L, 41L)) + when(socialGroupsClient.getFriendPresencePolicy(1L, CALLER_ACCOUNT_ID)) .thenReturn( GetFriendPresencePolicyResponse.newBuilder() .setError( @@ -1198,7 +1278,7 @@ void friendsVisibilityUpdatesCanonicalPolicy() { newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); when(socialGroupsClient.updateFriendPresencePolicy( 1L, - 41L, + CALLER_ACCOUNT_ID, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE)) .thenReturn( @@ -1235,7 +1315,7 @@ void friendsVisibilityUpdatesCanonicalPolicy() { Mockito.verify(socialGroupsClient) .updateFriendPresencePolicy( 1L, - 41L, + CALLER_ACCOUNT_ID, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); Mockito.verify(scriptEventPublisher) @@ -1253,7 +1333,7 @@ void friendsVisibilityUpdateFailsClosedWhenCanonicalPolicyUpdateIsUnavailable() socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); when(socialGroupsClient.updateFriendPresencePolicy( 1L, - 41L, + CALLER_ACCOUNT_ID, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE)) .thenReturn( @@ -1306,7 +1386,7 @@ void friendsVisibilityRejectsReservedHiddenStaffPolicy() { .isEqualTo( "ERROR INVALID_ARGUMENT HIDDEN_STAFF is reserved and cannot be set from gameplay"); Mockito.verify(socialGroupsClient, Mockito.never()) - .updateFriendPresencePolicy(Mockito.anyLong(), Mockito.anyLong(), Mockito.any()); + .updateFriendPresencePolicy(Mockito.anyLong(), Mockito.anyString(), Mockito.any()); } @Test @@ -1340,7 +1420,7 @@ void friendsUnspecifiedVisibilityUsesCanonicalFilterAlias() { newHandler( socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); when(socialGroupsClient.listFriends( - 1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY)) + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY)) .thenReturn( ListFriendsResponse.newBuilder() .setFilter(FriendRosterFilter.FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY) @@ -1359,6 +1439,7 @@ void friendsUnspecifiedVisibilityUsesCanonicalFilterAlias() { (FriendPresenceViewOutput) result.outputs().getFirst().payload(); assertThat(view.filter()).isEqualTo("UNSPECIFIED_VISIBILITY"); Mockito.verify(socialGroupsClient) - .listFriends(1L, 41L, FriendRosterFilter.FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY); + .listFriends( + 1L, CALLER_ACCOUNT_ID, FriendRosterFilter.FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index 08e9fda08d..cd3c5ac0ff 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 @@ -38,6 +38,8 @@ import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mockito; @@ -45,6 +47,8 @@ @SuppressWarnings("unchecked") class LoginCommandHandlerTest { + private static final String ACCOUNT_ID = "00000000-0000-4000-8000-000000000077"; + private static final String OTHER_ACCOUNT_ID = "00000000-0000-4000-8000-000000000099"; private static final String AUTH_TOKEN = "mock-jwt"; private final GameInstanceRepository gameInstanceRepository = @@ -69,7 +73,10 @@ void setUp() { stubSessionContext(bootstrapShell(1L, 1L)); when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("77").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_ID) + .build()); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 1L)) .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 1L))); sessionRoutingNormalizationService = @@ -241,6 +248,38 @@ void bareLoginInvalidZeroSessionIdReturnsInvalidArgument() { "ERROR INVALID_ARGUMENT sessionId must be positive", joinedOutputText(result.outputs())); } + @ParameterizedTest + @ValueSource( + strings = { + "77", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000007A", + " 00000000-0000-4000-8000-000000000077", + "0-0-4000-8000-77" + }) + void loginDeniesLegacyOrNonCanonicalAccountIdentity(String invalidAccount) { + when(accountClient.authenticate(anyString(), anyString())) + .thenReturn( + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(invalidAccount) + .build()); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); + var result = + handler.handle( + "1", + new TextCommand( + TextCommandType.LOGIN, + List.of("demo@example.com", "swordfish"), + "LOGIN demo@example.com swordfish"), + false); + assertFalse(result.commandResult().accepted()); + assertEquals(LoginCommandConstants.INVALID_ACCOUNT_CODE, result.commandResult().errorCode()); + ArgumentCaptor saved = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(saved.capture()); + assertNull(saved.getValue().accountId()); + } + @Test void invalidAccountIdZeroReturnsInvalidAccount() { TextCommand command = @@ -414,7 +453,7 @@ void bareLoginRejectsIncompletePersistedFirstPartyContextWhenRegistryEntryIsMiss new SessionContext( 1L, 22L, - "77", + ACCOUNT_ID, null, 0L, null, @@ -450,7 +489,7 @@ void bareLoginDoesNotFallBackToRawPersistedFirstPartyContextWhenTenantScopedSess new SessionContext( 1L, 22L, - "77", + ACCOUNT_ID, null, 0L, null, @@ -494,7 +533,7 @@ void successfulLoginStoresSessionContext() { net.firedevops.firemud.gamesession.service.SessionContext context = captor.getValue(); assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals("77", context.accountId()); + assertEquals(ACCOUNT_ID, context.accountId()); assertEquals(0L, context.characterId()); assertEquals(0L, context.gameInstanceId()); assertNull(context.roomInstanceId()); @@ -559,7 +598,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { new SessionContext( 1L, 22L, - "77", + ACCOUNT_ID, "demo@example.com", 88L, "Sora", @@ -580,7 +619,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { new SessionContext( 1L, 22L, - "77", + ACCOUNT_ID, "demo@example.com", 88L, "Sora", @@ -603,7 +642,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { SessionContext context = captor.getValue(); assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals("77", context.accountId()); + assertEquals(ACCOUNT_ID, context.accountId()); assertEquals(88L, context.characterId()); assertEquals(1L, context.gameInstanceId()); assertEquals("R-2045", context.roomInstanceId()); @@ -622,12 +661,15 @@ void loginAsDifferentAccountClearsCrossTenantProjectedPresenceBeforeSaving() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(OTHER_ACCOUNT_ID) + .build()); SessionContext existing = new SessionContext( 1L, 22L, - "77", + ACCOUNT_ID, "demo@example.com", 88L, "Sora", @@ -654,7 +696,7 @@ void loginAsDifferentAccountClearsCrossTenantProjectedPresenceBeforeSaving() { inOrder.verify(sessionContextService).save(savedContext.capture()); assertEquals(22L, existing.tenantId()); assertEquals(23L, savedContext.getValue().tenantId()); - assertEquals("99", savedContext.getValue().accountId()); + assertEquals(OTHER_ACCOUNT_ID, savedContext.getValue().accountId()); assertEquals(0L, savedContext.getValue().characterId()); assertEquals(0L, savedContext.getValue().gameInstanceId()); } @@ -670,7 +712,10 @@ void loginAsDifferentAccountClearsCrossTenantPresenceAfterProjectionNormalizatio when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(OTHER_ACCOUNT_ID) + .build()); stubSessionContext(staleGameplayContext(0L)); handler.handle("1", command, false); @@ -683,10 +728,10 @@ void loginAsDifferentAccountClearsCrossTenantPresenceAfterProjectionNormalizatio .clearGameplayBinding(clearedContext.capture(), eq("LOGIN_ACCOUNT_CHANGED")); inOrder.verify(sessionContextService).save(savedContext.capture()); assertEquals(22L, clearedContext.getValue().tenantId()); - assertEquals("77", clearedContext.getValue().accountId()); + assertEquals(ACCOUNT_ID, clearedContext.getValue().accountId()); assertFalse(clearedContext.getValue().hasGameplayBinding()); assertEquals(23L, savedContext.getValue().tenantId()); - assertEquals("99", savedContext.getValue().accountId()); + assertEquals(OTHER_ACCOUNT_ID, savedContext.getValue().accountId()); assertEquals(0L, savedContext.getValue().characterId()); assertEquals(0L, savedContext.getValue().gameInstanceId()); } @@ -702,12 +747,15 @@ void loginAsSameAccountClearsCrossTenantPresenceBeforeSaving() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("77").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_ID) + .build()); SessionContext existing = new SessionContext( 1L, 22L, - "77", + ACCOUNT_ID, "demo@example.com", 88L, "Sora", @@ -733,9 +781,9 @@ void loginAsSameAccountClearsCrossTenantPresenceBeforeSaving() { .clearGameplayBinding(existing, "LOGIN_TENANT_CHANGED"); inOrder.verify(sessionContextService).save(savedContext.capture()); assertEquals(22L, existing.tenantId()); - assertEquals("77", existing.accountId()); + assertEquals(ACCOUNT_ID, existing.accountId()); assertEquals(23L, savedContext.getValue().tenantId()); - assertEquals("77", savedContext.getValue().accountId()); + assertEquals(ACCOUNT_ID, savedContext.getValue().accountId()); assertEquals(0L, savedContext.getValue().characterId()); assertEquals(0L, savedContext.getValue().gameInstanceId()); } @@ -751,7 +799,10 @@ void loginAsSameAccountClearsCrossTenantPresenceAfterProjectionNormalization() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("77").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(ACCOUNT_ID) + .build()); stubSessionContext(staleGameplayContext(0L)); handler.handle("1", command, false); @@ -764,10 +815,10 @@ void loginAsSameAccountClearsCrossTenantPresenceAfterProjectionNormalization() { .clearGameplayBinding(clearedContext.capture(), eq("LOGIN_TENANT_CHANGED")); inOrder.verify(sessionContextService).save(savedContext.capture()); assertEquals(22L, clearedContext.getValue().tenantId()); - assertEquals("77", clearedContext.getValue().accountId()); + assertEquals(ACCOUNT_ID, clearedContext.getValue().accountId()); assertFalse(clearedContext.getValue().hasGameplayBinding()); assertEquals(23L, savedContext.getValue().tenantId()); - assertEquals("77", savedContext.getValue().accountId()); + assertEquals(ACCOUNT_ID, savedContext.getValue().accountId()); assertEquals(0L, savedContext.getValue().characterId()); assertEquals(0L, savedContext.getValue().gameInstanceId()); } @@ -784,12 +835,15 @@ void reloginAsDifferentAccountClearsExistingGameplayBinding() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(OTHER_ACCOUNT_ID) + .build()); SessionContext existing = new SessionContext( 1L, 22L, - "77", + ACCOUNT_ID, "demo@example.com", 88L, "Sora", @@ -815,7 +869,7 @@ void reloginAsDifferentAccountClearsExistingGameplayBinding() { .clearGameplayBinding(existing, "LOGIN_ACCOUNT_CHANGED"); inOrder.verify(sessionContextService).save(captor.capture()); SessionContext context = captor.getValue(); - assertEquals("99", context.accountId()); + assertEquals(OTHER_ACCOUNT_ID, context.accountId()); assertEquals("other@example.com", context.loginName()); assertEquals(0L, context.characterId()); assertNull(context.characterName()); @@ -842,7 +896,10 @@ void reloginAsDifferentAccountDoesNotReplaceContextWhenPresenceClearFails() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(OTHER_ACCOUNT_ID) + .build()); SessionContext existing = staleGameplayContext(1L); stubSessionContext(existing); Mockito.doThrow(new IllegalStateException("presence clear unavailable")) @@ -879,7 +936,7 @@ void reloginClearsStaleGameplayBindingBeforeRefreshingLoginContext() { SessionContext context = captor.getValue(); assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals("77", context.accountId()); + assertEquals(ACCOUNT_ID, context.accountId()); assertEquals(0L, context.characterId()); assertNull(context.characterName()); assertEquals(0L, context.gameInstanceId()); @@ -948,7 +1005,7 @@ void invalidCredentialsDropPartialProjectedRoutingBundleDuringFailedLoginCleanup new SessionContext( 1L, 22L, - "77", + ACCOUNT_ID, "demo@example.com", 88L, "Sora", @@ -987,7 +1044,10 @@ void authenticatedNonOwnerAccountIsAcceptedAndStored() { when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + AuthenticateResponse.newBuilder() + .setAuthToken(AUTH_TOKEN) + .setAccountId(OTHER_ACCOUNT_ID) + .build()); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -995,7 +1055,7 @@ void authenticatedNonOwnerAccountIsAcceptedAndStored() { assertEquals("Logged in as demo@example.com", joinedOutputText(result.outputs())); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); - assertEquals("99", captor.getValue().accountId()); + assertEquals(OTHER_ACCOUNT_ID, captor.getValue().accountId()); assertEquals("demo@example.com", captor.getValue().loginName()); assertEquals(77L, instance.getOwnerAccountId()); } @@ -1396,7 +1456,7 @@ private static SessionContext staleGameplayContext(long pointerVersion) { return new SessionContext( 1L, 22L, - "77", + ACCOUNT_ID, "demo@example.com", 88L, "Sora", @@ -1417,7 +1477,7 @@ private static SessionContext staleGameplayContextWithoutSelector(long pointerVe return new SessionContext( 1L, 22L, - "77", + ACCOUNT_ID, "demo@example.com", 88L, "Sora", 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 c761b12f12..071bcf71f9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -2,9 +2,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -44,6 +46,7 @@ import org.springframework.dao.DataAccessResourceFailureException; class PlayCommandHandlerTest { + private static final String ACCOUNT_ID = "5e1340f8-99c8-49fa-a4fe-5fc9d2075621"; private static final String PLAY_COMMAND_NAME = "PLAY"; private final SessionAuthenticationService sessionAuthenticationService = Mockito.mock(SessionAuthenticationService.class); @@ -100,7 +103,7 @@ void setUp() { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry); - when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong())) + when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -109,7 +112,7 @@ void setUp() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) @@ -131,7 +134,14 @@ void setUp() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); + .thenAnswer( + invocation -> + realmGrantResponse( + invocation.getArgument(0), + invocation.getArgument(1), + invocation.getArgument(2), + invocation.getArgument(3), + true)); when(sessionRoutingNormalizationService.normalizeProjectedContext( Mockito.any(SessionContext.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -163,7 +173,7 @@ void setUp() { @Test void playPromotesSessionIntoGameplay() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -178,7 +188,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -196,7 +206,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -214,7 +224,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -233,7 +243,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -251,13 +261,15 @@ void playPromotesSessionIntoGameplay() { var admissionOrder = Mockito.inOrder(accountClient, entityManagementClient); admissionOrder .verify(accountClient) - .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + .getTenantMembershipForRuntime( + Mockito.eq(ACCOUNT_ID), Mockito.eq("22"), Mockito.anyString()); admissionOrder .verify(accountClient) .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); admissionOrder .verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); Mockito.verify(entityManagementClient, never()) .findCharacterByName( Mockito.any(), Mockito.any(PlayableStateScope.class), Mockito.anyString()); @@ -272,7 +284,7 @@ void playFailsClosedWhenTenantHasMultiplePublicProductionRealmsAcrossWorlds() { .getFirst() .setPublicProductionRealm(true); SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult ambiguousDefaultResult = @@ -303,7 +315,7 @@ void playFailsClosedWhenTenantHasNoPublicProductionRealm() { .getFirst() .setPublicProductionRealm(false); SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -355,7 +367,7 @@ void playUsesSelectedTenantAuthorityWhenAnotherTenantHasNoPublicProductionRealm( "Maintenance World", List.of(realm("maintenance", "Maintenance Realm", 23L, 99L, true, false)))); SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -368,9 +380,11 @@ void playUsesSelectedTenantAuthorityWhenAnotherTenantHasNoPublicProductionRealm( assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); Mockito.verify(accountClient) - .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + .getTenantMembershipForRuntime( + Mockito.eq(ACCOUNT_ID), Mockito.eq("22"), Mockito.anyString()); Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @Test @@ -390,7 +404,7 @@ void playStillRejectsSelectedTenantWithoutPublicProductionRealm() { "Other Public World", List.of(realm("production", "Live Realm", 23L, 99L, true, false)))); SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -408,9 +422,9 @@ void playStillRejectsSelectedTenantWithoutPublicProductionRealm() { @Test void playRejectsModerationPolicyDeniedAdmission() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(moderationPolicyClient.evaluateGameplayAdmission(22L, 123L)) + when(moderationPolicyClient.evaluateGameplayAdmission(22L, ACCOUNT_ID)) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(false) @@ -422,6 +436,7 @@ void playRejectsModerationPolicyDeniedAdmission() { assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()).isEqualTo("MODERATION_POLICY_DENIED"); + verify(moderationPolicyClient).evaluateGameplayAdmission(22L, ACCOUNT_ID); Mockito.verify(sessionContextService, Mockito.never()).save(Mockito.any()); Mockito.verify(gameplayPresenceLifecycleService, Mockito.never()) .registerConnected(Mockito.any()); @@ -430,7 +445,7 @@ void playRejectsModerationPolicyDeniedAdmission() { @Test void playUsesPersistedAccountRosterCharacterForSelectedTarget() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 2L, 9007L)) .thenReturn(Optional.empty()); @@ -449,7 +464,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 9007L, "Emberline", @@ -467,7 +482,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 9007L, "Emberline", @@ -487,7 +502,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 9007L, "Emberline", @@ -507,15 +522,19 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { @Test void playWithoutCharacterSelectorShowsPersistedRosterCharacterName() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "7001", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "7001", + "Emberline", + "22", + ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -527,15 +546,19 @@ void playWithoutCharacterSelectorShowsPersistedRosterCharacterName() { @Test void playWithCaseVariedCharacterSelectorShowsPersistedRosterCharacterName() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "7001", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "7001", + "Emberline", + "22", + ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle( @@ -550,13 +573,17 @@ void playWithCaseVariedCharacterSelectorShowsPersistedRosterCharacterName() { @Test void playRejectsMalformedPersistedRosterCharacterId() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "abc", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "abc", + "Emberline", + "22", + ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle( @@ -582,10 +609,10 @@ void playRejectsMalformedPersistedRosterCharacterId() { @Test void playRejectsCharacterRosterFromAnotherAccountBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( "8008", "demo", "22", "999", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); @@ -601,13 +628,13 @@ void playRejectsCharacterRosterFromAnotherAccountBeforeBinding() { @Test void playRejectsCharacterRosterFromAnotherTenantBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "8008", "demo", "23", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "8008", "demo", "23", ACCOUNT_ID, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -620,22 +647,23 @@ void playRejectsCharacterRosterFromAnotherTenantBeforeBinding() { @Test void playRejectsDuplicatePersistedCharacterIdsBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); ListCharactersByAccountResponse roster = - characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + characterRoster( + "8008", "demo", "22", ACCOUNT_ID, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .toBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("8008") .setTenantId("22") - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setName("other") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .build(); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(roster); PlayCommandHandlingResult result = @@ -649,22 +677,23 @@ void playRejectsDuplicatePersistedCharacterIdsBeforeBinding() { @Test void playWithAmbiguousCharacterNameReturnsSelectionGuidanceBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); ListCharactersByAccountResponse roster = - characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + characterRoster( + "8008", "demo", "22", ACCOUNT_ID, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .toBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("8009") .setTenantId("22") - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setName("Demo") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .build(); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(roster); PlayCommandHandlingResult result = @@ -677,10 +706,10 @@ void playWithAmbiguousCharacterNameReturnsSelectionGuidanceBeforeBinding() { @Test void playWithEmptyCharacterRosterReturnsSelectionGuidanceBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(ListCharactersByAccountResponse.newBuilder().build()); PlayCommandHandlingResult result = @@ -693,22 +722,23 @@ void playWithEmptyCharacterRosterReturnsSelectionGuidanceBeforeBinding() { @Test void playWithoutCharacterSelectorReturnsSelectionGuidanceForMultipleCharacters() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); ListCharactersByAccountResponse roster = - characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + characterRoster( + "8008", "demo", "22", ACCOUNT_ID, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .toBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("8009") .setTenantId("22") - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setName("Emberline") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .build(); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(roster); PlayCommandHandlingResult result = @@ -721,7 +751,7 @@ void playWithoutCharacterSelectorReturnsSelectionGuidanceForMultipleCharacters() @Test void playWithUnmatchedCharacterSelectorReturnsGuidanceBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -736,10 +766,10 @@ void playWithUnmatchedCharacterSelectorReturnsGuidanceBeforeBinding() { @Test void playRejectsUnavailableCharacterRosterBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( ListCharactersByAccountResponse.newBuilder() .setError( @@ -762,7 +792,7 @@ void playResumeDoesNotPublishSpawnEvent() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -777,10 +807,14 @@ void playResumeDoesNotPublishSpawnEvent() { "SHARED"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( characterRoster( - "7001", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + "7001", + "Emberline", + "22", + ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -800,9 +834,10 @@ void playResumeDoesNotPublishSpawnEvent() { @Test void playIgnoresStaleExistingBindingAfterNormalization() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); SessionContext clearedExisting = - new SessionContext(9L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "old-jwt", 1L); + new SessionContext( + 9L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, null, "old-jwt", 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.of(clearedExisting)); @@ -817,7 +852,7 @@ void playIgnoresStaleExistingBindingAfterNormalization() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -839,12 +874,12 @@ void playIgnoresStaleExistingBindingAfterNormalization() { @Test void playIgnoresExistingBindingWithoutRoomRegion() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); SessionContext existingWithoutRoom = new SessionContext( 9L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -871,7 +906,7 @@ void playIgnoresExistingBindingWithoutRoomRegion() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -902,7 +937,7 @@ void playWithoutSessionReturnsLoginRequired() { @Test void playWithoutArgumentsReturnsInvalidArgument() { - SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -914,7 +949,7 @@ void playWithoutArgumentsReturnsInvalidArgument() { @Test void unknownWorldReturnsSelectionGuidance() { - SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -963,7 +998,7 @@ void playDoesNotAdmitV6QuarantinedPointerWithoutCatalogIdentity() { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry); - SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1019,7 +1054,7 @@ void retainedPointerWithUnknownStateScopeCannotBindOrSpawn() { scriptEventPublisher, meterRegistry); SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1031,13 +1066,14 @@ void retainedPointerWithUnknownStateScopeCannotBindOrSpawn() { Mockito.verify(sessionContextService, never()).save(Mockito.any()); Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); Mockito.verify(entityManagementClient, never()) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); Mockito.verify(scriptEventPublisher, never()).publishCommandEvent(Mockito.any(), Mockito.any()); } @Test void sandboxWithoutCharacterReturnsSelectionRequired() { - SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1058,7 +1094,7 @@ void sandboxWithoutCharacterReturnsSelectionRequired() { @Test void explicitRealmWithoutCharacterReturnsCharacterSelectionGuidance() { - SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1088,7 +1124,7 @@ void playRejectsIsolatedStateRealm() { .getRealms() .get(1) .setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); - SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1114,7 +1150,7 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "first-party:123", 0L, null, @@ -1150,13 +1186,13 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( void playDeniedByMembershipReturnsWorldAccessDenied() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(false) @@ -1188,7 +1224,7 @@ void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { new SessionContext( 1L, 23L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -1206,7 +1242,7 @@ void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(false) .setGameplayAdmissionAllowed(false) @@ -1232,13 +1268,13 @@ void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { void playNonPublicRealmRequiresExistingAdmissibleMembership() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(false) .setGameplayAdmissionAllowed(true) @@ -1276,14 +1312,14 @@ void playInvisibleRealmWithGrantedAccessContinuesAdmission() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); + .thenReturn(realmGrantResponse(true)); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( - Mockito.eq("123"), + Mockito.eq(ACCOUNT_ID), Mockito.eq("22"), Mockito.eq("sandbox"), Mockito.eq("preview"), @@ -1308,7 +1344,7 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( - Mockito.eq("123"), + Mockito.eq(ACCOUNT_ID), Mockito.eq("22"), Mockito.eq("sandbox"), Mockito.eq("preview"), @@ -1391,12 +1427,88 @@ void playInvisibleRealmWithUnavailableGrantFailsClosed() { Mockito.verify(sessionContextService, never()).save(Mockito.any()); } + @Test + void playMismatchedRealmGrantCorrelationFailsUnavailable() { + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(realmGrantResponse(true).toBuilder().setRealmSlug("other-realm").build()); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playGrantedRealmWithoutGrantGenerationFailsUnavailable() { + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(realmGrantResponse(true).toBuilder().setGrantVersion(0L).build()); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playMismatchedRealmGrantCorrelationFailsUnavailable() { + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(realmGrantResponse(true).toBuilder().setRealmSlug("other-realm").build()); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playGrantedRealmWithoutGrantGenerationFailsUnavailable() { + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(realmGrantResponse(true).toBuilder().setGrantVersion(0L).build()); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + @ParameterizedTest @ValueSource(strings = {"NOT_FOUND", "PERMISSION_DENIED"}) void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String errorCode) { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) @@ -1423,13 +1535,13 @@ void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String e void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(false) .setGameplayAdmissionAllowed(true) @@ -1453,13 +1565,13 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(false) @@ -1478,17 +1590,95 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "join_required"); } + @ParameterizedTest + @ValueSource( + strings = { + ACCOUNT_ID, + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "5E1340F8-99C8-49FA-A4FE-5FC9D2075621", + " 5e1340f8-99c8-49fa-a4fe-5fc9d2075621" + }) + void playWhenMembershipAuthorityAccountDoesNotExactlyMatchFailsClosed(String responseAccountId) { + SessionContext context = + new SessionContext( + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId(responseAccountId) + .setTenantId("22") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verify(moderationPolicyClient, never()) + .evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "123", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "5E1340F8-99C8-49FA-A4FE-5FC9D2075621", + " 5e1340f8-99c8-49fa-a4fe-5fc9d2075621" + }) + void playWhenMembershipAuthorityAccountDoesNotExactlyMatchFailsClosed(String responseAccountId) { + SessionContext context = + new SessionContext( + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId(responseAccountId) + .setTenantId("22") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verify(moderationPolicyClient, never()) + .evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString()); + } + @Test void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) @@ -1550,7 +1740,7 @@ void playWithUnavailableSessionStoreReturnsRetryableAuthorityFailure() { void playBlockedByEntitlementsReturnsBillingBlocked() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1580,7 +1770,7 @@ void playBlockedByEntitlementsReturnsBillingBlocked() { void playMapsNonAuthorityEntitlementFailureToBillingBlocked() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1612,7 +1802,7 @@ void playMapsNonAuthorityEntitlementFailureToBillingBlocked() { void playWhenMembershipAuthorityUnavailableFailsClosed() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) @@ -1644,7 +1834,7 @@ void playWhenMembershipAuthorityUnavailableFailsClosed() { void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { SessionContext context = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1674,7 +1864,8 @@ void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { @Test void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { SessionContext context = - new SessionContext(1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, null, "jwt-token"); + new SessionContext( + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, null, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -1689,7 +1880,7 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -1715,7 +1906,7 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -1734,7 +1925,7 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -1767,7 +1958,7 @@ private SessionContext previewRealmContext() { return new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 123L, "Emberline", @@ -1789,6 +1980,40 @@ private TextCommand previewRealmPlayCommand() { "PLAY sandbox preview Emberline"); } + private static GetRealmAccessGrantForRuntimeResponse realmGrantResponse(boolean granted) { + return realmGrantResponse(ACCOUNT_ID, "22", "sandbox", "preview", granted); + } + + private static GetRealmAccessGrantForRuntimeResponse realmGrantResponse( + String accountId, String tenantId, String worldSlug, String realmSlug, boolean granted) { + return GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setAccountId(accountId) + .setTenantId(tenantId) + .setWorldSlug(worldSlug) + .setRealmSlug(realmSlug) + .setGranted(granted) + .setGrantVersion(granted ? 3L : 0L) + .setEvaluatedAt(Instant.now().toString()) + .build(); + } + + private static GetRealmAccessGrantForRuntimeResponse realmGrantResponse(boolean granted) { + return realmGrantResponse(ACCOUNT_ID, "22", "sandbox", "preview", granted); + } + + private static GetRealmAccessGrantForRuntimeResponse realmGrantResponse( + String accountId, String tenantId, String worldSlug, String realmSlug, boolean granted) { + return GetRealmAccessGrantForRuntimeResponse.newBuilder() + .setAccountId(accountId) + .setTenantId(tenantId) + .setWorldSlug(worldSlug) + .setRealmSlug(realmSlug) + .setGranted(granted) + .setGrantVersion(granted ? 3L : 0L) + .setEvaluatedAt(Instant.now().toString()) + .build(); + } + private static GameplayCatalogProperties.World world( String slug, String displayName, List realms) { GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); @@ -1904,7 +2129,7 @@ void playDefensivelyDeniesFirstPartyContextAddedAfterTopLevelCheck() { .thenAnswer(invocation -> Optional.of(fixture.service.requireRetained(context))); SessionContext legacyContext = new SessionContext( - 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")) .thenReturn(Optional.of(legacyContext)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 237ec04168..7f8cbb5a25 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -75,6 +75,7 @@ @SuppressWarnings("unchecked") class SessionResumptionFlowTest { + private static final String ACCOUNT_ID = "5e1340f8-99c8-49fa-a4fe-5fc9d2075621"; private static final String LOGIN_PAYLOAD = "LOGIN demo@example.com swordfish"; private static final String PLAY_PAYLOAD = "PLAY demo production"; private static final String LOOK_PAYLOAD = "LOOK"; @@ -164,12 +165,12 @@ void setUp() { .thenReturn(CommandEnqueueResult.success()); when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken("jwt").setAccountId("77").build()); + AuthenticateResponse.newBuilder().setAuthToken("jwt").setAccountId(ACCOUNT_ID).build()); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("77") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) @@ -183,7 +184,7 @@ void setUp() { Mockito.anyString(), Mockito.anyString())) .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); - when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong())) + when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -208,7 +209,7 @@ void setUp() { net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") .setTenantId("22") - .setAccountId("77") + .setAccountId(ACCOUNT_ID) .setName("Emberline") .setLevel(12) .setPlayableStateScope( @@ -466,7 +467,7 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("77") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(false) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index ddbf4bc986..9a2b99d9f8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -89,6 +89,7 @@ @SuppressWarnings("unchecked") class TextCommandInterpreterTest { + private static final String ACCOUNT_ID = "5e1340f8-99c8-49fa-a4fe-5fc9d2075621"; private static final String PLAY_DEMO_PRODUCTION = "PLAY demo production"; private final CommandService commandService = Mockito.mock(CommandService.class); @@ -165,13 +166,13 @@ void setUp() { .thenReturn( AuthenticateResponse.newBuilder() .setAuthToken("auth-token") - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .build()); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) @@ -185,7 +186,7 @@ void setUp() { Mockito.anyString(), Mockito.anyString())) .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(true).build()); - when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong())) + when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -404,14 +405,14 @@ void setUp() { lookCacheService, new TextPlayerOutputRenderer(new PresentationProperties())); when(entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse.newBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") .setTenantId("22") - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setName("demo") .setLevel(12) .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) @@ -852,7 +853,9 @@ void gameplayAfterLoginBeforePlayReturnsPlayRequired() { @Test void gameplayWithRoomOnlyPartialShellStillReturnsPlayRequired() { ((InMemorySessionContextService) sessionContextService) - .save(new SessionContext(56L, 22L, "123", "demo@example.com", 0L, null, 0L, "R-7", null)); + .save( + new SessionContext( + 56L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "R-7", null)); TextCommandInterpretationResult interpretation = interpreter.interpret("56", "LOOK", false); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 8ecd774522..d575ecfa04 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -12,6 +12,7 @@ import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import net.firedevops.firemud.gamesession.test.GameplayCommandTestFixtures; +import net.firedevops.firemud.test.AccountRuntimeStubServer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -92,14 +93,17 @@ void browseCharactersReturnsStructuredCharacterList() { List.of(world("demo", 22L, 1L, false), world("sandbox", 23L, 2L, true))); Mockito.when( entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", + AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( ListCharactersByAccountResponse.newBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") .setTenantId("22") - .setAccountId("123") + .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(123L)) .setName("Emberline") .setLevel(12) .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) @@ -119,7 +123,11 @@ void browseCharactersReturnsStructuredCharacterList() { assertThat(output.characters()).hasSize(1); assertThat(output.characters().get(0).characterName()).isEqualTo("Emberline"); Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", + AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @Test @@ -140,14 +148,17 @@ void browseCharactersUsesIsolatedStateRealmRoster() { gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setGameInstanceId(41L); Mockito.when( entityManagementClient.listCharactersByAccount( - "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + "22", + AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "41", + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) .thenReturn( ListCharactersByAccountResponse.newBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("8001") .setTenantId("22") - .setAccountId("123") + .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(123L)) .setName("Forkline") .setLevel(5) .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) @@ -167,7 +178,10 @@ void browseCharactersUsesIsolatedStateRealmRoster() { .containsExactly("Forkline"); Mockito.verify(entityManagementClient) .listCharactersByAccount( - "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED); + "22", + AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "41", + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED); } @Test @@ -176,7 +190,10 @@ void browseCharactersFallsBackToUnspecifiedRosterScopeForNullRealmScope() { gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setStateScope(null); Mockito.when( entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED)) + "22", + AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED)) .thenReturn(ListCharactersByAccountResponse.newBuilder().build()); WorldsCommandHandler localHandler = new WorldsCommandHandler( @@ -189,6 +206,43 @@ void browseCharactersFallsBackToUnspecifiedRosterScopeForNullRealmScope() { assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); } + @Test + void charsRejectsNumericOrMismatchedAccountOwnersWithoutReturningRoster() { + gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); + var actor = GameplayCommandTestFixtures.worldBrowseDemo(); + for (String owner : + List.of( + "123", + "00000000-0000-0000-0000-000000000000", + AccountRuntimeStubServer.accountUuidForTestFixture(124L))) { + Mockito.when( + entityManagementClient.listCharactersByAccount( + "22", actor.accountId(), "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + ListCharactersByAccountResponse.newBuilder() + .addCharacters( + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId("7001") + .setTenantId("22") + .setAccountId(owner) + .setName("Other")) + .build()); + assertThat(handler.browseCharacters(actor, "demo", null)) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); + } + } + + @Test + void charsRejectsNonCanonicalCallerBeforeEntityRead() { + gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); + var actor = + new net.firedevops.firemud.gamesession.service.SessionContext( + 1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt"); + assertThat(handler.browseCharacters(actor, "demo", null)) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); + Mockito.verifyNoInteractions(entityManagementClient); + } + private static GameplayCatalogProperties.World world( String slug, long tenantId, long gameInstanceId, boolean requiresCharacterSelection) { GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 2d916a2844..a1b282b348 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import net.firedevops.firemud.gamesession.test.GameplayCommandTestFixtures; +import net.firedevops.firemud.test.AccountRuntimeStubServer; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -92,14 +93,17 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { void publishesCommandEventForGameplayScopedCharsBrowse() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 41L, false))); when(entityManagementClient.listCharactersByAccount( - "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + "22", + AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "41", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( ListCharactersByAccountResponse.newBuilder() .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") .setTenantId("22") - .setAccountId("123") + .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(123L)) .setName("Emberline") .setLevel(12) .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) @@ -121,7 +125,11 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { .extracting(output -> output.payload()) .isInstanceOf(CharacterBrowseViewOutput.class); Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount( + "22", + AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "41", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.eq(context), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java index c970c7cfe7..27892167f1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java @@ -2,25 +2,30 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamesession.health.GameplayLocalPathReadinessProbe.ProbeResult; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.gamesession.service.impl.RedisSessionContextService; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; class GameplayLocalPathReadinessProbeTest { private static final long PROBE_SESSION_ID_BASE = 9_223_372_036_854_770_000L; - private static final long PROBE_ACCOUNT_ID = 9_223_372_036_854_770_001L; + private static final String PROBE_ACCOUNT_ID = "00000000-0000-4000-8000-000000000001"; private static final long PROBE_CHARACTER_ID = 9_223_372_036_854_770_002L; @Test @@ -37,7 +42,7 @@ void sessionContextProbeReturnsUpWhenContextRoundTrips() { new SessionContext( sessionId, 0L, - Long.toString(PROBE_ACCOUNT_ID), + PROBE_ACCOUNT_ID, PROBE_CHARACTER_ID, 0L, "readiness-room-" + probeSequence, @@ -59,6 +64,49 @@ void sessionContextProbeReturnsUpWhenContextRoundTrips() { verify(sessionContextService).deleteBySessionId(0L, savedContext.sessionId()); } + @Test + void sessionContextProbeUsesCanonicalAccountIdentityAcceptedByRedisLookup() { + SessionContextService sessionContextService = mock(SessionContextService.class); + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + doAnswer( + invocation -> { + SessionContext context = invocation.getArgument(0, SessionContext.class); + when(valueOperations.get("sessionctx:0:" + context.sessionId() + ":context")) + .thenReturn(context); + return null; + }) + .when(sessionContextService) + .save(any(SessionContext.class)); + RedisSessionContextService strictLookup = new RedisSessionContextService(redisTemplate, 1000L); + when(sessionContextService.findByTenantAndSessionId(anyLong(), anyLong())) + .thenAnswer( + invocation -> + strictLookup.findByTenantAndSessionId( + invocation.getArgument(0, Long.class), invocation.getArgument(1, Long.class))); + + GameplayLocalPathReadinessProbe probe = + new GameplayLocalPathReadinessProbe(sessionContextService, redisTemplate); + + ProbeResult result = probe.probeSessionContextStore(); + + assertTrue(result.ready()); + assertEquals("ROUND_TRIP_OK", result.detail()); + ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(contextCaptor.capture()); + SessionContext savedContext = contextCaptor.getValue(); + assertEquals(PROBE_ACCOUNT_ID, savedContext.accountId()); + assertEquals(UUID.fromString(savedContext.accountId()).toString(), savedContext.accountId()); + assertTrue(savedContext.hasAccountIdentity()); + assertEquals( + Optional.of(savedContext), + strictLookup.findByTenantAndSessionId(savedContext.tenantId(), savedContext.sessionId())); + verify(sessionContextService).deleteBySessionId(0L, savedContext.sessionId()); + } + @Test void commandQueueProbeReturnsUpWhenQueueWriteRoundTrips() { SessionContextService sessionContextService = mock(SessionContextService.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java index bdae4a8cdc..2b2ef9403d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java @@ -1069,7 +1069,7 @@ void renderSuccessfulForOutputFormatsFriendDetailWithFriendsEnvelope() { new FriendPresenceViewOutput.Entry( 1, 77L, - 41L, + "00000000-0000-4000-8000-000000000041", "ONLINE", null, "Sora", @@ -1095,7 +1095,7 @@ void renderSuccessfulForOutputFormatsFriendDetailWithFriendsEnvelope() { assertThat(rendered) .isEqualTo( "OK FRIENDS\n" - + "Friend Sora [acct #41]\n" + + "Friend Sora [acct #00000000-0000-4000-8000-000000000041]\n" + "Link: #77\n" + "Status: online\n" + "Presence: online in Demo World / Ember Realm (active)\n" diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java index 638e0b2623..4052154f87 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java @@ -17,6 +17,7 @@ import org.mockito.Mockito; class SessionAuthenticationServiceTest { + private static final String ACCOUNT_UUID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; private final SessionContextService sessionContextService = Mockito.mock(SessionContextService.class); private final GameplayAdmissionPointerAuthorityService pointerAuthorityService = @@ -39,13 +40,34 @@ void setUp() { gameplayPresenceLifecycleService); } + @Test + void nonCanonicalRetainedAccountDoesNotAuthenticateOrNormalizeEvidence() { + properties.setRequireAuthenticatedCommands(true); + for (String invalid : + List.of( + "123", + "00000000-0000-0000-0000-000000000000", + " " + ACCOUNT_UUID, + ACCOUNT_UUID.toUpperCase(java.util.Locale.ROOT))) { + SessionContext retained = new SessionContext(41L, 22L, invalid, 7001L, 1L, "R-1", "jwt"); + when(sessionContextService.findBySessionId(41L)).thenReturn(Optional.of(retained)); + when(sessionContextService.findByTenantAndSessionId(22L, 41L)) + .thenReturn(Optional.of(retained)); + assertFalse(service.isAuthenticated("41")); + assertTrue(service.resolveSessionContext("41").isEmpty()); + assertSame(retained, service.normalizeResolvedContext(retained)); + } + verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verifyNoInteractions(gameplayPresenceLifecycleService, pointerAuthorityService); + } + @Test void resolveSessionContextClearsStaleGameplayBindingButKeepsLogin() { SessionContext stale = new SessionContext( 41L, 22L, - "123", + ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", @@ -66,13 +88,13 @@ void resolveSessionContextClearsStaleGameplayBindingButKeepsLogin() { Optional resolved = service.resolveSessionContext("41"); assertTrue(resolved.isPresent()); - assertEquals("123", resolved.orElseThrow().accountId()); + assertEquals(ACCOUNT_UUID, resolved.orElseThrow().accountId()); assertEquals(0L, resolved.orElseThrow().gameInstanceId()); assertEquals(0L, resolved.orElseThrow().characterId()); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); verify(gameplayPresenceLifecycleService).clearGameplayBinding(stale, "STALE_ADMISSION_POINTER"); - assertEquals("123", captor.getValue().accountId()); + assertEquals(ACCOUNT_UUID, captor.getValue().accountId()); assertEquals(0L, captor.getValue().gameInstanceId()); assertEquals(0L, captor.getValue().pointerVersion()); } @@ -81,7 +103,7 @@ void resolveSessionContextClearsStaleGameplayBindingButKeepsLogin() { void resolveSessionContextClearsGameplayBindingWhenRoutingBundleIsIncomplete() { SessionContext incomplete = new SessionContext( - 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 1L, "R-1", "jwt"); + 41L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 1L, "R-1", "jwt"); when(sessionContextService.findBySessionId(41L)).thenReturn(Optional.of(incomplete)); when(sessionContextService.findByTenantAndSessionId(22L, 41L)) .thenReturn(Optional.of(incomplete)); @@ -89,7 +111,7 @@ void resolveSessionContextClearsGameplayBindingWhenRoutingBundleIsIncomplete() { Optional resolved = service.resolveSessionContext("41"); assertTrue(resolved.isPresent()); - assertEquals("123", resolved.orElseThrow().accountId()); + assertEquals(ACCOUNT_UUID, resolved.orElseThrow().accountId()); assertEquals(0L, resolved.orElseThrow().gameInstanceId()); verify(sessionContextService).save(Mockito.any(SessionContext.class)); verify(gameplayPresenceLifecycleService) @@ -102,7 +124,7 @@ void resolveSessionContextClearsGameplayBindingWhenRuntimeTargetAuthorityIsAmbig new SessionContext( 41L, 22L, - "123", + ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", @@ -139,7 +161,7 @@ void resolveSessionContextKeepsCurrentGameplayBindingWhenPointerMatches() { new SessionContext( 41L, 22L, - "123", + ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", @@ -172,7 +194,7 @@ void resolveUnverifiedSessionContextWithTenantIdNormalizesResolvedContext() { new SessionContext( 41L, 22L, - "123", + ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", @@ -192,7 +214,7 @@ void resolveUnverifiedSessionContextWithTenantIdNormalizesResolvedContext() { Optional resolved = service.resolveUnverifiedSessionContext(22L, 41L); assertTrue(resolved.isPresent()); - assertEquals("123", resolved.orElseThrow().accountId()); + assertEquals(ACCOUNT_UUID, resolved.orElseThrow().accountId()); assertEquals(0L, resolved.orElseThrow().gameInstanceId()); verify(sessionContextService).save(Mockito.any(SessionContext.class)); verify(gameplayPresenceLifecycleService).clearGameplayBinding(stale, "STALE_ADMISSION_POINTER"); @@ -204,7 +226,7 @@ void resolveUnverifiedSessionContextFailsClosedWhenTenantScopedSessionIsMissing( new SessionContext( 41L, 22L, - "123", + ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", @@ -260,7 +282,7 @@ void resolveByGameplayIdentityNormalizesResolvedContext() { new SessionContext( 41L, 22L, - "123", + ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", @@ -292,7 +314,7 @@ void resolveByGameplayNameKeepsCurrentContextWhenPointerMatches() { new SessionContext( 41L, 22L, - "123", + ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java index 0b6d52ee7f..38d0bee86e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java @@ -7,20 +7,47 @@ import org.junit.jupiter.api.Test; class SessionContextTest { + private static final String ACCOUNT_UUID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + + @Test + void accountIdentityRequiresCanonicalNonNilUuid() { + assertTrue(new SessionContext(1L, 22L, ACCOUNT_UUID, 3L, 4L, "jwt").hasAccountIdentity()); + for (String invalid : + java.util.Arrays.asList( + null, + "", + "123", + "not-an-account", + "00000000-0000-0000-0000-000000000000", + ACCOUNT_UUID.toUpperCase(java.util.Locale.ROOT), + " " + ACCOUNT_UUID, + "0-0-4000-8000-123")) { + assertFalse(new SessionContext(1L, 22L, invalid, 3L, 4L, "jwt").hasAccountIdentity()); + } + } @Test void preservesLegacyAndSyntheticRuntimeRoomIdsVerbatim() { SessionContext legacyNumeric = - new SessionContext(1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "1", "jwt"); + new SessionContext( + 1L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 41L, "1", "jwt"); SessionContext legacyPrefixed = new SessionContext( - 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "room-1", "jwt"); + 1L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 41L, "room-1", "jwt"); SessionContext legacyUppercasePrefixed = new SessionContext( - 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "ROOM-1", "jwt"); + 1L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 41L, "ROOM-1", "jwt"); SessionContext syntheticProbe = new SessionContext( - 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "readiness-room-1", "jwt"); + 1L, + 22L, + ACCOUNT_UUID, + "demo@example.com", + 7001L, + "Emberline", + 41L, + "readiness-room-1", + "jwt"); assertEquals("1", legacyNumeric.roomInstanceId()); assertEquals("room-1", legacyPrefixed.roomInstanceId()); @@ -34,7 +61,7 @@ void hasPartialPersistedFirstPartyConnectContextDetectsMissingConnectRequest() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_UUID, "first-party:123", 0L, null, @@ -60,7 +87,7 @@ void hasPartialPersistedFirstPartyConnectContextIgnoresStandardGameplaySession() new SessionContext( 1L, 22L, - "123", + ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", @@ -85,7 +112,7 @@ void hasPartialPersistedFirstPartyConnectContextDetectsMissingConnectScope() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_UUID, "first-party:123", 0L, null, @@ -135,12 +162,12 @@ void oldSelectorFragmentsFailClosedEvenWithoutAccountIdentity() { void hasGameplayRegionBindingRequiresGameInstanceCharacterAndRoom() { SessionContext complete = new SessionContext( - 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); + 1L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); SessionContext missingRoom = new SessionContext( - 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, null, "jwt"); + 1L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 41L, null, "jwt"); SessionContext missingCharacter = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 41L, "R-1", "jwt"); + new SessionContext(1L, 22L, ACCOUNT_UUID, "demo@example.com", 0L, null, 41L, "R-1", "jwt"); assertTrue(complete.hasGameplayRegionBinding()); assertFalse(missingRoom.hasGameplayRegionBinding()); @@ -150,13 +177,14 @@ void hasGameplayRegionBindingRequiresGameInstanceCharacterAndRoom() { @Test void hasGameplayBindingTreatsPartialGameplayShellsAsBound() { SessionContext gameOnly = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 41L, null, "jwt"); + new SessionContext(1L, 22L, ACCOUNT_UUID, "demo@example.com", 0L, null, 41L, null, "jwt"); SessionContext characterOnly = - new SessionContext(1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 0L, null, "jwt"); + new SessionContext( + 1L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 0L, null, "jwt"); SessionContext roomOnly = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "R-1", "jwt"); + new SessionContext(1L, 22L, ACCOUNT_UUID, "demo@example.com", 0L, null, 0L, "R-1", "jwt"); SessionContext blank = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "jwt"); + new SessionContext(1L, 22L, ACCOUNT_UUID, "demo@example.com", 0L, null, 0L, null, "jwt"); assertTrue(gameOnly.hasGameplayBinding()); assertTrue(characterOnly.hasGameplayBinding()); @@ -168,12 +196,12 @@ void hasGameplayBindingTreatsPartialGameplayShellsAsBound() { void hasGameplayIdentityRequiresPositiveGameInstanceAndCharacter() { SessionContext complete = new SessionContext( - 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); + 1L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); SessionContext missingGameInstance = new SessionContext( - 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 0L, "R-1", "jwt"); + 1L, 22L, ACCOUNT_UUID, "demo@example.com", 7001L, "Emberline", 0L, "R-1", "jwt"); SessionContext missingCharacter = - new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 41L, "R-1", "jwt"); + new SessionContext(1L, 22L, ACCOUNT_UUID, "demo@example.com", 0L, null, 41L, "R-1", "jwt"); assertTrue(complete.hasGameplayIdentity()); assertFalse(missingGameInstance.hasGameplayIdentity()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java index f71d635e40..8d66a7e4d9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java @@ -1,6 +1,8 @@ package net.firedevops.firemud.gamesession.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.time.Instant; @@ -20,6 +22,10 @@ import org.mockito.Mockito; class AccountPresenceQueryServiceImplTest { + private static final String VIEWER_ACCOUNT_ID = "00000000-0000-4000-8000-000000000002"; + private static final String ONLINE_ACCOUNT_ID = "00000000-0000-4000-8000-000000000003"; + private static final String OFFLINE_ACCOUNT_ID = "00000000-0000-4000-8000-000000000004"; + @Test void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { GameplayPresenceService presenceService = Mockito.mock(GameplayPresenceService.class); @@ -35,13 +41,16 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.containsAll(List.of("3", "4")) && ids.size() == 2))) + ids -> + ids != null + && ids.containsAll(List.of(ONLINE_ACCOUNT_ID, OFFLINE_ACCOUNT_ID)) + && ids.size() == 2))) .thenReturn( java.util.Map.of( - "4", + OFFLINE_ACCOUNT_ID, new AccountRecentPresenceState( 1L, - "4", + OFFLINE_ACCOUNT_ID, 2L, "SHARED", "sandbox", @@ -52,10 +61,13 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.containsAll(List.of("3", "4")) && ids.size() == 2))) + ids -> + ids != null + && ids.containsAll(List.of(ONLINE_ACCOUNT_ID, OFFLINE_ACCOUNT_ID)) + && ids.size() == 2))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, List.of( new GameplayPresence( 97L, @@ -65,7 +77,7 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { "sandbox", "production", 17L, - "3", + ONLINE_ACCOUNT_ID, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -78,10 +90,12 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, "2", List.of("3", "4")); + var result = + service.queryAccountPresence( + 1L, VIEWER_ACCOUNT_ID, List.of(ONLINE_ACCOUNT_ID, OFFLINE_ACCOUNT_ID)); assertEquals(2, result.size()); - assertEquals("3", result.get(0).accountId()); + assertEquals(ONLINE_ACCOUNT_ID, result.get(0).accountId()); assertEquals(true, result.get(0).online()); assertEquals(2L, result.get(0).gameInstanceId()); assertEquals("sandbox", result.get(0).worldSlug()); @@ -94,7 +108,7 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { net.firedevops.firemud.gamesession.service.GameplayPresenceActivityState.EXPLICIT_AFK, result.get(0).activityState()); assertEquals(null, result.get(0).recentDisposition()); - assertEquals("4", result.get(1).accountId()); + assertEquals(OFFLINE_ACCOUNT_ID, result.get(1).accountId()); assertEquals(false, result.get(1).online()); assertEquals(2L, result.get(1).gameInstanceId()); assertEquals("sandbox", result.get(1).worldSlug()); @@ -122,13 +136,13 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, new AccountRecentPresenceState( 1L, - "3", + ONLINE_ACCOUNT_ID, 9L, "SHARED", "sandbox", @@ -139,10 +153,10 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, List.of( new GameplayPresence( 97L, @@ -152,7 +166,7 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { "sandbox", "production", 18L, - "3", + ONLINE_ACCOUNT_ID, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -165,7 +179,7 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, "2", List.of("3")); + var result = service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(ONLINE_ACCOUNT_ID)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -188,13 +202,13 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, new AccountRecentPresenceState( 1L, - "3", + ONLINE_ACCOUNT_ID, 2L, "SHARED", "sandbox", @@ -205,10 +219,10 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, List.of( new GameplayPresence( 97L, @@ -218,7 +232,7 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin "sandbox", "production", 0L, - "3", + ONLINE_ACCOUNT_ID, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -231,7 +245,7 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, "2", List.of("3")); + var result = service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(ONLINE_ACCOUNT_ID)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -257,13 +271,13 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, new AccountRecentPresenceState( 1L, - "3", + ONLINE_ACCOUNT_ID, 2L, "SHARED", "sandbox", @@ -274,10 +288,10 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, List.of( new GameplayPresence( 97L, @@ -287,7 +301,7 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna " ", "production", 17L, - "3", + ONLINE_ACCOUNT_ID, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -300,7 +314,7 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, "2", List.of("3")); + var result = service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(ONLINE_ACCOUNT_ID)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -326,15 +340,15 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn(Map.of()); when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, List.of( new GameplayPresence( 97L, @@ -344,7 +358,7 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { "sandbox", "production", 18L, - "3", + ONLINE_ACCOUNT_ID, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -360,7 +374,7 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { "sandbox", "production", 17L, - "3", + ONLINE_ACCOUNT_ID, 100L, "Ben", GameplayPresenceRole.PLAYER, @@ -373,7 +387,7 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, "2", List.of("3")); + var result = service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(ONLINE_ACCOUNT_ID)); assertEquals(1, result.size()); assertEquals(true, result.get(0).online()); @@ -397,13 +411,13 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, new AccountRecentPresenceState( 1L, - "3", + ONLINE_ACCOUNT_ID, 2L, "SHARED", "sandbox", @@ -414,10 +428,10 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, List.of( new GameplayPresence( 97L, @@ -427,7 +441,7 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { "sandbox", "production", 17L, - "3", + ONLINE_ACCOUNT_ID, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -441,7 +455,7 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L), pointer("sandbox", "Builder Sandbox", "preview", "Preview Realm", 1L, 2L, 18L))); - var result = service.queryAccountPresence(1L, "2", List.of("3")); + var result = service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(ONLINE_ACCOUNT_ID)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -467,13 +481,13 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, new AccountRecentPresenceState( 1L, - "3", + ONLINE_ACCOUNT_ID, 2L, "SHARED", "sandbox", @@ -484,10 +498,10 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, List.of( new GameplayPresence( 97L, @@ -497,7 +511,7 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { "sandbox", "production", 17L, - "3", + ONLINE_ACCOUNT_ID, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -522,7 +536,7 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { "", "ALLOW_NEW"))); - var result = service.queryAccountPresence(1L, "2", List.of("3")); + var result = service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(ONLINE_ACCOUNT_ID)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -548,15 +562,15 @@ void queryAccountPresenceTreatsCaseInsensitiveLiveRoutingIdentityAsCurrent() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn(Map.of()); when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("3") && ids.size() == 1))) + ids -> ids != null && ids.contains(ONLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "3", + ONLINE_ACCOUNT_ID, List.of( new GameplayPresence( 97L, @@ -566,7 +580,7 @@ void queryAccountPresenceTreatsCaseInsensitiveLiveRoutingIdentityAsCurrent() { "Sandbox", "Production", 17L, - "3", + ONLINE_ACCOUNT_ID, 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -579,7 +593,7 @@ void queryAccountPresenceTreatsCaseInsensitiveLiveRoutingIdentityAsCurrent() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, "2", List.of("3")); + var result = service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(ONLINE_ACCOUNT_ID)); assertEquals(1, result.size()); assertEquals(true, result.get(0).online()); @@ -604,13 +618,13 @@ void queryAccountPresenceTreatsCaseInsensitiveRecentRoutingIdentityAsCurrent() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("4") && ids.size() == 1))) + ids -> ids != null && ids.contains(OFFLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn( Map.of( - "4", + OFFLINE_ACCOUNT_ID, new AccountRecentPresenceState( 1L, - "4", + OFFLINE_ACCOUNT_ID, 2L, "SHARED", "Sandbox", @@ -621,14 +635,14 @@ void queryAccountPresenceTreatsCaseInsensitiveRecentRoutingIdentityAsCurrent() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains("4") && ids.size() == 1))) + ids -> ids != null && ids.contains(OFFLINE_ACCOUNT_ID) && ids.size() == 1))) .thenReturn(Map.of()); when(pointerAuthorityService.listByRuntimeTarget(1L, 2L)) .thenReturn( List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, "2", List.of("4")); + var result = service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(OFFLINE_ACCOUNT_ID)); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -638,6 +652,38 @@ void queryAccountPresenceTreatsCaseInsensitiveRecentRoutingIdentityAsCurrent() { assertEquals("Live Realm", result.get(0).realmDisplayName()); } + @Test + void queryAccountPresenceRejectsNonCanonicalAccountIdsBeforeReadingPresence() { + GameplayPresenceService presenceService = Mockito.mock(GameplayPresenceService.class); + AccountRecentPresenceService recentPresenceService = + Mockito.mock(AccountRecentPresenceService.class); + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + AccountPresenceQueryServiceImpl service = + new AccountPresenceQueryServiceImpl( + presenceService, + new GameplayPresenceActivityResolver(new PresenceProperties()), + recentPresenceService, + pointerAuthorityService); + + for (String invalidAccountId : + List.of( + "3", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000000A", + " " + ONLINE_ACCOUNT_ID, + ONLINE_ACCOUNT_ID + " ")) { + assertThrows( + IllegalArgumentException.class, + () -> service.queryAccountPresence(1L, invalidAccountId, List.of(ONLINE_ACCOUNT_ID))); + assertThrows( + IllegalArgumentException.class, + () -> service.queryAccountPresence(1L, VIEWER_ACCOUNT_ID, List.of(invalidAccountId))); + } + + verifyNoInteractions(presenceService, recentPresenceService, pointerAuthorityService); + } + private static GameplayAdmissionPointerSnapshot pointer( String worldSlug, String worldDisplayName, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java index 445226cea6..c54efdcfa5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.entity.GameInstance; @@ -34,6 +35,8 @@ @ExtendWith(OutputCaptureExtension.class) class CommandServiceImplTest { + private static final String ACCOUNT_UUID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + @Test void rateLimitFailurePropagatesError() { TickService tickService = Mockito.mock(TickService.class); @@ -181,8 +184,15 @@ void enqueueRejectsNegativeSessionIdBeforeSessionLookup() { } @Test - void enqueueRejectsUnsupportedAccountIdBeforePersistenceOrQueueing() { - for (String accountId : List.of("6ba7b810-9dad-11d1-80b4-00c04fd430c8", "0", "-1")) { + void enqueueRejectsNonCanonicalAccountUuidBeforePersistenceOrQueueing() { + for (String accountId : + List.of( + "42", + "00000000-0000-0000-0000-000000000000", + ACCOUNT_UUID.toUpperCase(java.util.Locale.ROOT), + " " + ACCOUNT_UUID + " ", + "not-a-uuid", + " ")) { TickService tickService = Mockito.mock(TickService.class); SessionRateLimiter rateLimiter = Mockito.mock(SessionRateLimiter.class); GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); @@ -207,11 +217,7 @@ void enqueueRejectsUnsupportedAccountIdBeforePersistenceOrQueueing() { assertTrue(result.hasError()); assertEquals("INVALID_ARGUMENT", result.errorCode()); - assertEquals( - accountId.equals("0") || accountId.equals("-1") - ? "accountId must be positive" - : "accountId must be numeric", - result.errorMessage()); + assertEquals("accountId must be a canonical non-nil UUID", result.errorMessage()); verify(commandRepository, never()).save(Mockito.any()); verify(tickService, never()) .enqueueCommand( @@ -355,7 +361,8 @@ void gameplayCommandsQueueAgainstGameInstanceWhenSessionContextHasOne() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of( + new SessionContext(17L, 9L, ACCOUNT_UUID, "demo", 44L, "char", 99L, "R-1", "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); CommandServiceImpl service = @@ -374,8 +381,8 @@ void gameplayCommandsQueueAgainstGameInstanceWhenSessionContextHasOne() { org.mockito.ArgumentCaptor commandCaptor = org.mockito.ArgumentCaptor.forClass(GameplayCommand.class); verify(commandRepository).save(commandCaptor.capture()); - assertEquals(3L, commandCaptor.getValue().getAccountId()); - assertNull(commandCaptor.getValue().getAccountUuid()); + assertEquals(UUID.fromString(ACCOUNT_UUID), commandCaptor.getValue().getAccountUuid()); + assertNull(commandCaptor.getValue().getAccountId()); verify(tickService, times(1)).enqueueCommand(9L, 99L, result.commandId(), "look", false); verify(scriptEventPublisher, times(1)) .publishCommandEvent(Mockito.any(SessionContext.class), Mockito.any(GameplayCommand.class)); @@ -431,7 +438,7 @@ void gameplayCommandsPersistCurrentRuntimeScopeForDurableCommandEventFallback() new SessionContext( 17L, 9L, - "3", + ACCOUNT_UUID, "demo", 44L, "char", @@ -484,7 +491,8 @@ void gameplayCommandFailsBeforePersistenceWhenRuntimeOwnershipIsNotEstablished() Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( Optional.of( - new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "region-99", "jwt"))); + new SessionContext( + 17L, 9L, ACCOUNT_UUID, "demo", 44L, "char", 99L, "region-99", "jwt"))); Mockito.when(runtimeRegionStatusRepository.findByTenantIdAndGameInstanceId(9L, 99L)) .thenReturn(Optional.empty()); CommandServiceImpl service = @@ -526,7 +534,8 @@ void gameplayCommandFailsClosedWhenRuntimeOwnershipReadFails() { Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( Optional.of( - new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "region-99", "jwt"))); + new SessionContext( + 17L, 9L, ACCOUNT_UUID, "demo", 44L, "char", 99L, "region-99", "jwt"))); Mockito.when(runtimeRegionStatusRepository.findByTenantIdAndGameInstanceId(9L, 99L)) .thenThrow(new IllegalStateException("runtime ownership unavailable")); CommandServiceImpl service = @@ -617,7 +626,21 @@ void staleNormalizedGameplaySessionFailsClosedWithoutBootstrapRoutingBundle() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); SessionContext cleared = new SessionContext( - 17L, 9L, "3", "demo", 0L, null, 0L, null, "jwt", null, 99L, null, null, 0L, null); + 17L, + 9L, + ACCOUNT_UUID, + "demo", + 0L, + null, + 0L, + null, + "jwt", + null, + 99L, + null, + null, + 0L, + null); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn(Optional.of(cleared)); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); @@ -660,7 +683,8 @@ void enqueueAddsGameplayLoggingContextWhenSessionIsBound() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of( + new SessionContext(17L, 9L, ACCOUNT_UUID, "demo", 44L, "char", 99L, "R-1", "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); Mockito.doAnswer( invocation -> { @@ -710,7 +734,8 @@ void loginCommandsAreRedactedFromLogs(CapturedOutput output) { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of( + new SessionContext(17L, 9L, ACCOUNT_UUID, "demo", 44L, "char", 99L, "R-1", "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); CommandServiceImpl service = newCommandService( @@ -749,7 +774,7 @@ void loginCommandPersistsBootstrapRoutingMetadataFromAuthority() { new SessionContext( 17L, 9L, - "3", + ACCOUNT_UUID, "demo", 0L, null, @@ -813,7 +838,7 @@ void loginCommandPersistsBootstrapRoutingMetadataFromUnambiguousRuntimeAuthority GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) - .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, "3", "demo", "jwt"))); + .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, ACCOUNT_UUID, "demo", "jwt"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -865,7 +890,7 @@ void loginCommandDropsBootstrapRoutingMetadataWhenRuntimeAuthorityIsAmbiguous() GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) - .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, "3", "demo", "jwt"))); + .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, ACCOUNT_UUID, "demo", "jwt"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -930,7 +955,7 @@ void loginCommandDropsBootstrapRoutingMetadataWhenSingularRuntimeAuthorityIsInco GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) - .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, "3", "demo", "jwt"))); + .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, ACCOUNT_UUID, "demo", "jwt"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -987,7 +1012,7 @@ void gameplayCommandRepairsPartialSessionRoutingMetadataFromAuthority() { new SessionContext( 17L, 9L, - "3", + ACCOUNT_UUID, "demo", 44L, "char", @@ -1054,8 +1079,21 @@ void gameplayCommandRepairsPointerOnlySessionRoutingMetadataFromRuntimeAuthority .thenReturn( Optional.of( new SessionContext( - 17L, 9L, "3", "demo", 44L, "char", 99L, "R-1", "jwt", null, 99L, null, null, - 17L, "SHARED"))); + 17L, + 9L, + ACCOUNT_UUID, + "demo", + 44L, + "char", + 99L, + "R-1", + "jwt", + null, + 99L, + null, + null, + 17L, + "SHARED"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -1112,7 +1150,7 @@ void gameplayCommandUsesActiveGameplayRuntimeAuthorityBeforeBootstrapRuntime() { new SessionContext( 17L, 9L, - "3", + ACCOUNT_UUID, "demo", 44L, "char", @@ -1184,7 +1222,7 @@ void gameplayCommandRepairsStaleCompleteSessionRoutingMetadataFromCurrentAuthori new SessionContext( 17L, 9L, - "3", + ACCOUNT_UUID, "demo", 0L, null, @@ -1253,7 +1291,7 @@ void gameplayCommandDropsStaleCompleteSessionRoutingMetadataWhenCurrentAuthority new SessionContext( 17L, 9L, - "3", + ACCOUNT_UUID, "demo", 0L, null, @@ -1308,7 +1346,7 @@ void gameplayCommandDropsPartialSessionRoutingMetadataWhenAuthorityCannotRepairI new SessionContext( 17L, 9L, - "3", + ACCOUNT_UUID, "demo", 44L, "char", @@ -1363,7 +1401,7 @@ void gameplayCommandDropsSessionRoutingMetadataWhenCurrentSelectorPointerIsIncom new SessionContext( 17L, 9L, - "3", + ACCOUNT_UUID, "demo", 44L, "char", @@ -1428,7 +1466,8 @@ void queueValidationFailureMarksPersistedCommandFailed() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of( + new SessionContext(17L, 9L, ACCOUNT_UUID, "demo", 44L, "char", 99L, "R-1", "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); Mockito.doThrow(new IllegalArgumentException("bad command")) .when(tickService) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java index e6567e6906..a53872b893 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java @@ -34,7 +34,15 @@ class DefaultGameplayPresenceLifecycleServiceTest { void registerConnectedUpdatesLiveAndRecentPresence() { SessionContext context = new SessionContext( - 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); + 41L, + 22L, + net.firedevops.firemud.test.AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1021", + ""); service.registerConnected(context); @@ -54,7 +62,15 @@ void recordActivityUpdatesLiveAndRecentPresence() { void clearGameplayBindingPublishesExitAndRemovesLivePresenceWithoutDisconnecting() { SessionContext context = new SessionContext( - 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); + 41L, + 22L, + net.firedevops.firemud.test.AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1021", + ""); service.clearGameplayBinding(context, "STALE_ADMISSION_POINTER"); @@ -71,7 +87,16 @@ void clearGameplayBindingPublishesExitAndRemovesLivePresenceWithoutDisconnecting @Test void clearGameplayBindingSkipsExitWithoutGameplayRegionBinding() { SessionContext context = - new SessionContext(41L, 22L, "123", "demo@example.com", 0L, null, 0L, null, ""); + new SessionContext( + 41L, + 22L, + net.firedevops.firemud.test.AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "demo@example.com", + 0L, + null, + 0L, + null, + ""); service.clearGameplayBinding(context, "LOGIN_FAILED"); @@ -86,7 +111,15 @@ void clearGameplayBindingSkipsExitWithoutGameplayRegionBinding() { void recordDisconnectedWritesRecentPresenceBeforeRemovingLivePresence() { whenGameplayContextPresent( new SessionContext( - 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 1L, "R-1021", "")); + 41L, + 22L, + net.firedevops.firemud.test.AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1021", + "")); service.recordDisconnected(41L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); @@ -109,7 +142,15 @@ void recordDisconnectedWritesRecentPresenceBeforeRemovingLivePresence() { void recordDisconnectedPreservesCanonicalLogoutEventId() { SessionContext context = new SessionContext( - 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); + 41L, + 22L, + net.firedevops.firemud.test.AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1021", + ""); whenGameplayContextPresent(context); service.recordDisconnected(41L, AccountRecentPresenceDisposition.LOGOUT); @@ -141,7 +182,16 @@ private void whenGameplayContextPresent(SessionContext context) { @Test void recordDisconnectedSkipsExitWhenNormalizationClearsStaleGameplayBinding() { SessionContext cleared = - new SessionContext(41L, 22L, "123", "demo@example.com", 0L, null, 0L, null, ""); + new SessionContext( + 41L, + 22L, + net.firedevops.firemud.test.AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "demo@example.com", + 0L, + null, + 0L, + null, + ""); Mockito.when(sessionRoutingNormalizationService.resolveProjectedSessionContext("41")) .thenReturn(Optional.of(cleared)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 6710e33f35..7b8dac5a44 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -2819,7 +2819,9 @@ void getGameplayCommandStatusReturnsLedgerRecordForAdminCaller() { command.setTenantId(1L); command.setGameInstanceId(7L); command.setSessionId(41L); - command.setAccountId(9L); + command.setAccountId( + 9L); // Private retained evidence must never be projected as Account identity. + command.setAccountUuid(java.util.UUID.fromString("00000000-0000-4000-8000-000000000009")); command.setCharacterId(44L); command.setCommandName("LOOK"); command.setSanitizedCommandText("LOOK"); @@ -3019,6 +3021,8 @@ public void onNext(GetGameplayCommandStatusResponse value) { } }); + assertEquals( + "00000000-0000-4000-8000-000000000009", responseRef.get().getCommand().getAccountId()); assertEquals("cmd-123", responseRef.get().getCommand().getCommandId()); assertEquals("STAGED", responseRef.get().getCommand().getExecutionOutcome()); assertEquals("LOOK", responseRef.get().getCommand().getSanitizedCommandText()); @@ -3105,6 +3109,23 @@ public void onNext(GetGameplayCommandStatusResponse value) { assertEquals( Instant.parse("2026-04-15T00:00:01Z").toEpochMilli(), responseRef.get().getCommand().getStagedAtMs()); + for (java.util.UUID absentOrNil : java.util.Arrays.asList(null, new java.util.UUID(0L, 0L))) { + command.setAccountUuid(absentOrNil); + service.getGameplayCommandStatus( + GetGameplayCommandStatusRequest.newBuilder() + .setTenantId("1") + .setGameInstanceId("7") + .setCommandId("cmd-123") + .build(), + new NoopObserver<>() { + @Override + public void onNext(GetGameplayCommandStatusResponse value) { + responseRef.set(value); + } + }); + assertEquals("", responseRef.get().getCommand().getAccountId()); + assertEquals(9L, command.getAccountId()); + } } @Test 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 59559e0116..b12053c53d 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 @@ -49,6 +49,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.IpConnectionLimiter; import net.firedevops.firemud.gamesession.service.PingService; +import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.TickService; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionRequest; @@ -87,6 +88,8 @@ import tools.jackson.databind.json.JsonMapper; class GameSessionGrpcServiceTest { + private static final String VIEWER_ACCOUNT_ID = "00000000-0000-4000-8000-000000000002"; + private static final String TARGET_ACCOUNT_ID = "00000000-0000-4000-8000-000000000007"; private static final String OPERATOR_NAMESPACE = "world-runtime"; private static final String OPERATOR_LOGGING_IDENTITY = "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; @@ -114,6 +117,28 @@ void tearDown() { SessionContext.clear(); } + private static QueryAccountPresenceResponse captureAccountPresenceResponse( + GameSessionGrpcService service, QueryAccountPresenceRequest request) { + AtomicReference ref = new AtomicReference<>(); + service.queryAccountPresence( + request, + new StreamObserver<>() { + @Override + public void onNext(QueryAccountPresenceResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + return ref.get(); + } + private static GameSessionGrpcService newService( PingService pingService, GameInstanceService gameInstanceService, @@ -292,12 +317,14 @@ void queryAccountPresenceReturnsMappedSnapshots() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of()); - Mockito.when(accountPresenceQueryService.queryAccountPresence(1L, "42", List.of("7"))) + SessionContext.setContext(VIEWER_ACCOUNT_ID, List.of(), Map.of()); + Mockito.when( + accountPresenceQueryService.queryAccountPresence( + 1L, VIEWER_ACCOUNT_ID, List.of(TARGET_ACCOUNT_ID))) .thenReturn( List.of( new AccountPresenceSnapshot( - "7", + TARGET_ACCOUNT_ID, true, 9L, "ISOLATED", @@ -324,48 +351,35 @@ void queryAccountPresenceReturnsMappedSnapshots() { meterRegistry, ipLimiter); - AtomicReference ref = new AtomicReference<>(); - service.queryAccountPresence( - QueryAccountPresenceRequest.newBuilder() - .setTenantId("1") - .setViewerAccountId("42") - .addAccountIds("7") - .build(), - new StreamObserver<>() { - @Override - public void onNext(QueryAccountPresenceResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - fail(t); - } - - @Override - public void onCompleted() {} - }); - - assertEquals(1, ref.get().getPresencesCount()); - assertEquals("7", ref.get().getPresences(0).getAccountId()); - assertEquals(true, ref.get().getPresences(0).getOnline()); - assertEquals("demo", ref.get().getPresences(0).getWorldSlug()); - assertEquals("Demo World", ref.get().getPresences(0).getWorldDisplayName()); - assertEquals(17L, ref.get().getPresences(0).getPointerVersion()); - assertEquals("production", ref.get().getPresences(0).getRealmSlug()); - assertEquals("Live Realm", ref.get().getPresences(0).getRealmDisplayName()); - assertEquals("Ben", ref.get().getPresences(0).getCharacterName()); + QueryAccountPresenceResponse response = + captureAccountPresenceResponse( + service, + QueryAccountPresenceRequest.newBuilder() + .setTenantId("1") + .setViewerAccountId(VIEWER_ACCOUNT_ID) + .addAccountIds(TARGET_ACCOUNT_ID) + .build()); + + assertEquals(1, response.getPresencesCount()); + assertEquals(TARGET_ACCOUNT_ID, response.getPresences(0).getAccountId()); + assertEquals(true, response.getPresences(0).getOnline()); + assertEquals("demo", response.getPresences(0).getWorldSlug()); + assertEquals("Demo World", response.getPresences(0).getWorldDisplayName()); + assertEquals(17L, response.getPresences(0).getPointerVersion()); + assertEquals("production", response.getPresences(0).getRealmSlug()); + assertEquals("Live Realm", response.getPresences(0).getRealmDisplayName()); + assertEquals("Ben", response.getPresences(0).getCharacterName()); assertEquals( Instant.parse("2026-04-11T06:15:30Z").toEpochMilli(), - ref.get().getPresences(0).getLastSeenAtMs()); + response.getPresences(0).getLastSeenAtMs()); assertEquals( net.firedevops.firemud.gamesession.v1.AccountRecentPresenceDisposition .ACCOUNT_RECENT_PRESENCE_DISPOSITION_TRANSPORT_LOSS, - ref.get().getPresences(0).getRecentDisposition()); + response.getPresences(0).getRecentDisposition()); } @Test - void queryAccountPresenceRejectsMalformedAccountId() { + void queryAccountPresenceRejectsMalformedAndLegacyAccountIdsBeforeCallingPresenceService() { PingService pingService = Mockito.mock(PingService.class); GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); @@ -376,7 +390,7 @@ void queryAccountPresenceRejectsMalformedAccountId() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of()); + SessionContext.setContext(VIEWER_ACCOUNT_ID, List.of(), Map.of()); GameSessionGrpcService service = newService( pingService, @@ -389,35 +403,30 @@ void queryAccountPresenceRejectsMalformedAccountId() { meterRegistry, ipLimiter); - AtomicReference ref = new AtomicReference<>(); - service.queryAccountPresence( - QueryAccountPresenceRequest.newBuilder() - .setTenantId("1") - .setViewerAccountId("42") - .addAccountIds("abc") - .build(), - new StreamObserver<>() { - @Override - public void onNext(QueryAccountPresenceResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - fail(t); - } - - @Override - public void onCompleted() {} - }); - - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be a number", ref.get().getError().getMessage()); + for (String invalidAccountId : + List.of( + "abc", + "42", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000000A", + " " + TARGET_ACCOUNT_ID)) { + QueryAccountPresenceResponse response = + captureAccountPresenceResponse( + service, + QueryAccountPresenceRequest.newBuilder() + .setTenantId("1") + .setViewerAccountId(VIEWER_ACCOUNT_ID) + .addAccountIds(invalidAccountId) + .build()); + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + assertEquals( + "accountId must be a canonical non-nil Account UUID", response.getError().getMessage()); + } Mockito.verifyNoInteractions(accountPresenceQueryService); } @Test - void queryAccountPresenceRejectsZeroAccountId() { + void queryAccountPresenceRejectsMalformedViewerAccountIdsBeforeCallingPresenceService() { PingService pingService = Mockito.mock(PingService.class); GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); @@ -428,7 +437,7 @@ void queryAccountPresenceRejectsZeroAccountId() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of()); + SessionContext.setContext(VIEWER_ACCOUNT_ID, List.of(), Map.of()); GameSessionGrpcService service = newService( pingService, @@ -441,30 +450,25 @@ void queryAccountPresenceRejectsZeroAccountId() { meterRegistry, ipLimiter); - AtomicReference ref = new AtomicReference<>(); - service.queryAccountPresence( - QueryAccountPresenceRequest.newBuilder() - .setTenantId("1") - .setViewerAccountId("42") - .addAccountIds("0") - .build(), - new StreamObserver<>() { - @Override - public void onNext(QueryAccountPresenceResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - fail(t); - } - - @Override - public void onCompleted() {} - }); - - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + for (String invalidViewerAccountId : + List.of( + "42", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000000A", + " " + VIEWER_ACCOUNT_ID)) { + QueryAccountPresenceResponse response = + captureAccountPresenceResponse( + service, + QueryAccountPresenceRequest.newBuilder() + .setTenantId("1") + .setViewerAccountId(invalidViewerAccountId) + .addAccountIds(TARGET_ACCOUNT_ID) + .build()); + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + assertEquals( + "viewerAccountId must be a canonical non-nil Account UUID", + response.getError().getMessage()); + } Mockito.verifyNoInteractions(accountPresenceQueryService); } @@ -480,7 +484,7 @@ void queryAccountPresenceRejectsTooManyAccountIdsBeforeParsing() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext("42", List.of(), Map.of()); + SessionContext.setContext(VIEWER_ACCOUNT_ID, List.of(), Map.of()); GameSessionGrpcService service = newService( pingService, @@ -494,9 +498,11 @@ void queryAccountPresenceRejectsTooManyAccountIdsBeforeParsing() { ipLimiter); QueryAccountPresenceRequest.Builder request = - QueryAccountPresenceRequest.newBuilder().setTenantId("1").setViewerAccountId("42"); + QueryAccountPresenceRequest.newBuilder() + .setTenantId("1") + .setViewerAccountId(VIEWER_ACCOUNT_ID); for (int index = 0; index < 101; index++) { - request.addAccountIds(index == 100 ? "not-a-number" : Long.toString(index + 1L)); + request.addAccountIds(index == 100 ? "not-a-number" : TARGET_ACCOUNT_ID); } AtomicReference ref = new AtomicReference<>(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java index b8ec61c099..fdde518dea 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java @@ -10,6 +10,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.time.Duration; @@ -34,6 +35,7 @@ import org.springframework.data.redis.serializer.SerializationException; class RedisAccountRecentPresenceServiceTest { + private static final String ACCOUNT_ID = "00000000-0000-4000-8000-000000000123"; @Test void recordDisconnectPersistsRoutingBundleFromLivePresence() { @@ -54,7 +56,7 @@ void recordDisconnectPersistsRoutingBundleFromLivePresence() { new SessionContext( 41L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -76,7 +78,7 @@ void recordDisconnectPersistsRoutingBundleFromLivePresence() { "demo", "production", 17L, - "123", + ACCOUNT_ID, 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -101,15 +103,18 @@ void recordDisconnectPersistsRoutingBundleFromLivePresence() { ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); - verify(redisTemplate).watch("accountrecentpresence:22:123"); + .set( + eq("accountrecentpresence:22:" + ACCOUNT_ID), + stateCaptor.capture(), + eq(Duration.ofMinutes(5))); + verify(redisTemplate).watch("accountrecentpresence:22:" + ACCOUNT_ID); verify(redisTemplate).multi(); verify(redisTemplate).exec(); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); assertEquals(22L, state.tenantId()); - assertEquals("123", state.accountId()); + assertEquals(ACCOUNT_ID, state.accountId()); assertEquals(101L, state.gameInstanceId()); assertEquals("demo", state.worldSlug()); assertEquals("production", state.realmSlug()); @@ -137,7 +142,7 @@ void recordDisconnectIgnoresLivePresenceWhenNormalizationClearsGameplayBinding() new SessionContext( 41L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 0L, null, @@ -159,7 +164,7 @@ void recordDisconnectIgnoresLivePresenceWhenNormalizationClearsGameplayBinding() "demo", "production", 17L, - "123", + ACCOUNT_ID, 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -185,7 +190,10 @@ void recordDisconnectIgnoresLivePresenceWhenNormalizationClearsGameplayBinding() ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); + .set( + eq("accountrecentpresence:22:" + ACCOUNT_ID), + stateCaptor.capture(), + eq(Duration.ofMinutes(5))); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); @@ -214,7 +222,7 @@ void recordDisconnectIgnoresLivePresenceWhenContextOnlyRetainsPartialGameplayShe new SessionContext( 41L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 0L, null, @@ -236,7 +244,7 @@ void recordDisconnectIgnoresLivePresenceWhenContextOnlyRetainsPartialGameplayShe "demo", "production", 17L, - "123", + ACCOUNT_ID, 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -262,7 +270,10 @@ void recordDisconnectIgnoresLivePresenceWhenContextOnlyRetainsPartialGameplayShe ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); + .set( + eq("accountrecentpresence:22:" + ACCOUNT_ID), + stateCaptor.capture(), + eq(Duration.ofMinutes(5))); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); @@ -291,7 +302,7 @@ void recordDisconnectUsesContextRoutingWhenLivePresenceRoutingFieldsArePartial() new SessionContext( 41L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -313,7 +324,7 @@ void recordDisconnectUsesContextRoutingWhenLivePresenceRoutingFieldsArePartial() "demo", null, 17L, - "123", + ACCOUNT_ID, 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -339,7 +350,10 @@ void recordDisconnectUsesContextRoutingWhenLivePresenceRoutingFieldsArePartial() ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); + .set( + eq("accountrecentpresence:22:" + ACCOUNT_ID), + stateCaptor.capture(), + eq(Duration.ofMinutes(5))); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); @@ -358,7 +372,7 @@ void unreadableRecentPresenceFailsClosedWithoutOverwritingRetainedEvidence() { ValueOperations valueOperations = Mockito.mock(ValueOperations.class); when(redisTemplate.opsForValue()).thenReturn(valueOperations); stubTransactionExecution(redisTemplate); - when(valueOperations.get("accountrecentpresence:22:123")) + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)) .thenThrow(new SerializationException("old AccountRecentPresenceState record shape")); GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); @@ -373,9 +387,9 @@ void unreadableRecentPresenceFailsClosedWithoutOverwritingRetainedEvidence() { presenceProperties, () -> 1_700_000_000_000L); SessionContext context = - new SessionContext(41L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "jwt"); + new SessionContext(41L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, null, "jwt"); - assertEquals(Map.of(), service.findByAccountIds(22L, List.of("123"))); + assertEquals(Map.of(), service.findByAccountIds(22L, List.of(ACCOUNT_ID))); service.recordConnected(context); verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); @@ -384,6 +398,96 @@ void unreadableRecentPresenceFailsClosedWithoutOverwritingRetainedEvidence() { verify(redisTemplate, never()).delete(anyString()); } + @Test + void findByAccountIdsDoesNotExposeMalformedRetainedAccountIdentity() { + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)) + .thenReturn( + new AccountRecentPresenceState( + 22L, "123", 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS)); + + RedisAccountRecentPresenceService service = + newService(redisTemplate, Mockito.mock(GameplayPresenceService.class)); + + assertEquals(Map.of(), service.findByAccountIds(22L, List.of(ACCOUNT_ID))); + verify(redisTemplate, never()).delete(anyString()); + verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); + } + + @Test + void findByAccountIdsReturnsExactCanonicalAccountState() { + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + AccountRecentPresenceState state = + new AccountRecentPresenceState( + 22L, ACCOUNT_ID, 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)).thenReturn(state); + RedisAccountRecentPresenceService service = + newService(redisTemplate, Mockito.mock(GameplayPresenceService.class)); + + assertEquals(Map.of(ACCOUNT_ID, state), service.findByAccountIds(22L, List.of(ACCOUNT_ID))); + } + + @Test + void recordConnectedPreservesReadableRetainedStateWithMalformedAccountIdentity() { + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + stubTransactionExecution(redisTemplate); + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)) + .thenReturn( + new AccountRecentPresenceState( + 22L, "123", 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS)); + GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); + when(gameplayPresenceService.findConnectedBySessionId(41L)).thenReturn(Optional.empty()); + + newService(redisTemplate, gameplayPresenceService).recordConnected(testContext()); + + verify(redisTemplate).watch("accountrecentpresence:22:" + ACCOUNT_ID); + verify(redisTemplate).unwatch(); + verify(redisTemplate, never()).multi(); + verify(redisTemplate, never()).exec(); + verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); + verify(redisTemplate, never()).delete(anyString()); + } + + @Test + void malformedCallerAccountIdsDoNotReadOrWriteRecentPresence() { + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); + RedisAccountRecentPresenceService service = newService(redisTemplate, gameplayPresenceService); + + for (String accountId : + List.of( + "123", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000000A", + " " + ACCOUNT_ID, + ACCOUNT_ID + " ")) { + assertEquals(Map.of(), service.findByAccountIds(22L, List.of(accountId))); + service.recordConnected( + new SessionContext(41L, 22L, accountId, "demo@example.com", 0L, null, 0L, null, "jwt")); + } + + verify(valueOperations, never()).get(anyString()); + verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); + verify(redisTemplate, never()).watch(anyString()); + verifyNoInteractions(gameplayPresenceService); + } + @Test void recordConnectedRetriesAfterWatchedValueChanges() { @SuppressWarnings("unchecked") @@ -394,11 +498,11 @@ void recordConnectedRetriesAfterWatchedValueChanges() { stubTransactionExecution(redisTemplate); AccountRecentPresenceState retained = new AccountRecentPresenceState( - 22L, "123", 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); + 22L, ACCOUNT_ID, 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); AccountRecentPresenceState concurrentReplacement = new AccountRecentPresenceState( - 22L, "123", 1_699_999_999_500L, AccountRecentPresenceDisposition.LOGOUT); - when(valueOperations.get("accountrecentpresence:22:123")) + 22L, ACCOUNT_ID, 1_699_999_999_500L, AccountRecentPresenceDisposition.LOGOUT); + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)) .thenReturn(retained, concurrentReplacement); when(redisTemplate.exec()).thenReturn(null, List.of("OK")); @@ -408,12 +512,12 @@ void recordConnectedRetriesAfterWatchedValueChanges() { service.recordConnected(testContext()); - verify(redisTemplate, times(2)).watch("accountrecentpresence:22:123"); + verify(redisTemplate, times(2)).watch("accountrecentpresence:22:" + ACCOUNT_ID); verify(redisTemplate, times(2)).multi(); verify(redisTemplate, times(2)).exec(); - verify(valueOperations, times(2)).get("accountrecentpresence:22:123"); + verify(valueOperations, times(2)).get("accountrecentpresence:22:" + ACCOUNT_ID); verify(valueOperations, times(2)) - .set(eq("accountrecentpresence:22:123"), any(), eq(Duration.ofMinutes(5))); + .set(eq("accountrecentpresence:22:" + ACCOUNT_ID), any(), eq(Duration.ofMinutes(5))); } @Test @@ -426,8 +530,8 @@ void recordConnectedStopsAfterEightWatchedConflictsWithoutCommittingTheProjectio stubTransactionExecution(redisTemplate); AccountRecentPresenceState retained = new AccountRecentPresenceState( - 22L, "123", 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); - when(valueOperations.get("accountrecentpresence:22:123")).thenReturn(retained); + 22L, ACCOUNT_ID, 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)).thenReturn(retained); when(redisTemplate.exec()).thenReturn(null); GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); @@ -436,14 +540,14 @@ void recordConnectedStopsAfterEightWatchedConflictsWithoutCommittingTheProjectio service.recordConnected(testContext()); - verify(redisTemplate, times(8)).watch("accountrecentpresence:22:123"); + verify(redisTemplate, times(8)).watch("accountrecentpresence:22:" + ACCOUNT_ID); verify(redisTemplate, times(8)).multi(); verify(redisTemplate, times(8)).exec(); - verify(valueOperations, times(8)).get("accountrecentpresence:22:123"); + verify(valueOperations, times(8)).get("accountrecentpresence:22:" + ACCOUNT_ID); // Each null EXEC represents a WATCH conflict, so none of the queued replacement writes // committed. verify(valueOperations, times(8)) - .set(eq("accountrecentpresence:22:123"), any(), eq(Duration.ofMinutes(5))); + .set(eq("accountrecentpresence:22:" + ACCOUNT_ID), any(), eq(Duration.ofMinutes(5))); verify(redisTemplate, never()).delete(anyString()); } @@ -457,8 +561,8 @@ void recordActivityStopsAfterEightWatchedConflictsWithoutCommittingTheProjection stubTransactionExecution(redisTemplate); AccountRecentPresenceState retained = new AccountRecentPresenceState( - 22L, "123", 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); - when(valueOperations.get("accountrecentpresence:22:123")).thenReturn(retained); + 22L, ACCOUNT_ID, 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)).thenReturn(retained); when(redisTemplate.exec()).thenReturn(null); SessionRoutingNormalizationService sessionRoutingNormalizationService = @@ -472,14 +576,14 @@ void recordActivityStopsAfterEightWatchedConflictsWithoutCommittingTheProjection service.recordActivity(41L); - verify(redisTemplate, times(8)).watch("accountrecentpresence:22:123"); + verify(redisTemplate, times(8)).watch("accountrecentpresence:22:" + ACCOUNT_ID); verify(redisTemplate, times(8)).multi(); verify(redisTemplate, times(8)).exec(); - verify(valueOperations, times(8)).get("accountrecentpresence:22:123"); + verify(valueOperations, times(8)).get("accountrecentpresence:22:" + ACCOUNT_ID); // Each null EXEC represents a WATCH conflict, so none of the queued replacement writes // committed. verify(valueOperations, times(8)) - .set(eq("accountrecentpresence:22:123"), any(), eq(Duration.ofMinutes(5))); + .set(eq("accountrecentpresence:22:" + ACCOUNT_ID), any(), eq(Duration.ofMinutes(5))); verify(redisTemplate, never()).delete(anyString()); } @@ -493,8 +597,8 @@ void recordConnectedDoesNotRetryWriteWhenConflictRevealsUnreadableReplacement() stubTransactionExecution(redisTemplate); AccountRecentPresenceState retained = new AccountRecentPresenceState( - 22L, "123", 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); - when(valueOperations.get("accountrecentpresence:22:123")) + 22L, ACCOUNT_ID, 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)) .thenReturn(retained) .thenThrow(new SerializationException("concurrent replacement has old record shape")); when(redisTemplate.exec()).thenReturn(null); @@ -505,13 +609,13 @@ void recordConnectedDoesNotRetryWriteWhenConflictRevealsUnreadableReplacement() service.recordConnected(testContext()); - verify(redisTemplate, times(2)).watch("accountrecentpresence:22:123"); + verify(redisTemplate, times(2)).watch("accountrecentpresence:22:" + ACCOUNT_ID); verify(redisTemplate).multi(); verify(redisTemplate).exec(); verify(redisTemplate).unwatch(); // The first queued SET was rejected by EXEC; the unreadable replacement prevents a retry SET. verify(valueOperations) - .set(eq("accountrecentpresence:22:123"), any(), eq(Duration.ofMinutes(5))); + .set(eq("accountrecentpresence:22:" + ACCOUNT_ID), any(), eq(Duration.ofMinutes(5))); } @Test @@ -522,7 +626,7 @@ void recordConnectedPreservesTypeMismatchedRetainedValue() { ValueOperations valueOperations = Mockito.mock(ValueOperations.class); when(redisTemplate.opsForValue()).thenReturn(valueOperations); stubTransactionExecution(redisTemplate); - when(valueOperations.get("accountrecentpresence:22:123")).thenReturn("legacy value"); + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)).thenReturn("legacy value"); GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); when(gameplayPresenceService.findConnectedBySessionId(41L)).thenReturn(Optional.empty()); @@ -530,7 +634,7 @@ void recordConnectedPreservesTypeMismatchedRetainedValue() { service.recordConnected(testContext()); - verify(redisTemplate).watch("accountrecentpresence:22:123"); + verify(redisTemplate).watch("accountrecentpresence:22:" + ACCOUNT_ID); verify(redisTemplate).unwatch(); verify(redisTemplate, never()).multi(); verify(redisTemplate, never()).exec(); @@ -546,7 +650,7 @@ void recordConnectedPropagatesRedisReadOutage() { ValueOperations valueOperations = Mockito.mock(ValueOperations.class); when(redisTemplate.opsForValue()).thenReturn(valueOperations); stubTransactionExecution(redisTemplate); - when(valueOperations.get("accountrecentpresence:22:123")) + when(valueOperations.get("accountrecentpresence:22:" + ACCOUNT_ID)) .thenThrow(new IllegalStateException("Redis unavailable")); GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); @@ -582,7 +686,7 @@ private static RedisAccountRecentPresenceService newService( } private static SessionContext testContext() { - return new SessionContext(41L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "jwt"); + return new SessionContext(41L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, null, "jwt"); } @SuppressWarnings("unchecked") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java index 08f44e47c1..703f04a6e4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java @@ -113,4 +113,27 @@ void wrongRetainedValueFailsClosedWithoutOverwritingEvidence() { verify(redisTemplate, never()).delete(key); verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); } + + @Test + void unregisterRetainsTypedButUnverifiableContext() { + String key = "sessionctx:first-party:91:connect-context"; + FirstPartyConnectContext incomplete = mock(FirstPartyConnectContext.class); + store.put(key, incomplete); + registry.unregister(91L); + assertEquals(incomplete, store.get(key)); + verify(redisTemplate, never()).delete(key); + } + + @Test + void unregisterRetainsSignedContextWhenCurrentTargetCannotBeVerified() { + String key = "sessionctx:first-party:91:connect-context"; + FirstPartyConnectContext original = fixture.context(); + store.put(key, original); + when(fixture.routes.readCurrentTarget( + net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture.TENANT)) + .thenReturn(null); + registry.unregister(91L); + assertEquals(original, store.get(key)); + verify(redisTemplate, never()).delete(key); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java index 424f99490f..b13b383af4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java @@ -27,6 +27,9 @@ @SuppressWarnings("unchecked") class RedisGameplayPresenceServiceTest { + private static final String GOD_ACCOUNT_ID = "00000000-0000-4000-8000-000000000001"; + private static final String PLAYER_ACCOUNT_ID = "00000000-0000-4000-8000-000000000002"; + private static final String OTHER_ACCOUNT_ID = "00000000-0000-4000-8000-000000000003"; private static final Duration TTL = Duration.ofMillis(1000L); private final RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); @@ -46,7 +49,8 @@ void setUp() { @Test void registerConnectedStoresPresenceAndIndexesByGameInstance() { SessionContext context = - new SessionContext(1L, 22L, "102", "player@example.com", 202L, "Ben", 7L, "R-1", null); + new SessionContext( + 1L, 22L, PLAYER_ACCOUNT_ID, "player@example.com", 202L, "Ben", 7L, "R-1", null); service.registerConnected(context); @@ -61,16 +65,37 @@ void registerConnectedStoresPresenceAndIndexesByGameInstance() { .equals("Ben")), org.mockito.Mockito.eq(TTL)); verify(setOperations).add("gameplaypresence:22:7:sessions", "1"); - verify(setOperations).add("gameplaypresence:22:account:102:sessions", "1"); + verify(setOperations) + .add("gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions", "1"); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); - verify(redisTemplate).expire("gameplaypresence:22:account:102:sessions", TTL); + verify(redisTemplate) + .expire("gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions", TTL); + } + + @Test + void registerAndQueryRejectNonCanonicalAccountIdsWithoutPresenceMutation() { + for (String accountId : + List.of( + "102", + "00000000-0000-0000-0000-000000000000", + "00000000-0000-4000-8000-00000000000A", + " " + PLAYER_ACCOUNT_ID, + PLAYER_ACCOUNT_ID + " ")) { + service.registerConnected( + new SessionContext( + 1L, 22L, accountId, "player@example.com", 202L, "Ben", 7L, "R-1", null)); + assertEquals(Map.of(), service.listConnectedByAccountIds(22L, List.of(accountId))); + } + + verifyNoPresenceMutation(); + Mockito.verifyNoInteractions(setOperations, valueOperations); } @Test void registerConnectedClassifiesInvalidJwtAsPlayer() { SessionContext context = new SessionContext( - 1L, 22L, "102", "player@example.com", 202L, "Ben", 7L, "R-1", "not-a-jwt"); + 1L, 22L, PLAYER_ACCOUNT_ID, "player@example.com", 202L, "Ben", 7L, "R-1", "not-a-jwt"); service.registerConnected(context); @@ -90,16 +115,17 @@ void registerConnectedClassifiesInvalidJwtAsPlayer() { void listConnectedByGameInstanceSortsGodsFirstAndPrunesMissingSessions() { String godJwt = jwtUtil.generateToken( - "1", + GOD_ACCOUNT_ID, Map.of( "accountId", - "1", + GOD_ACCOUNT_ID, "globalRoles", List.of("platformAdmin"), "scopedRoles", Map.of())); SessionContext godContext = - new SessionContext(1L, 22L, "1", "god@example.com", 101L, "Aster", 7L, "R-1", godJwt); + new SessionContext( + 1L, 22L, GOD_ACCOUNT_ID, "god@example.com", 101L, "Aster", 7L, "R-1", godJwt); service.registerConnected(godContext); when(setOperations.members("gameplaypresence:22:7:sessions")) @@ -112,7 +138,7 @@ void listConnectedByGameInstanceSortsGodsFirstAndPrunesMissingSessions() { 7L, "demo", "production", - "1", + GOD_ACCOUNT_ID, 101L, "Aster", GameplayPresenceRole.GOD, @@ -142,7 +168,7 @@ void listConnectedByGameInstancePrunesMalformedSessionIndexEntry() { 7L, "demo", "production", - "1", + GOD_ACCOUNT_ID, 101L, "Aster", GameplayPresenceRole.GOD, @@ -168,7 +194,7 @@ void removeBySessionIdRemovesValueAndSetMembership() { 7L, "demo", "production", - "102", + PLAYER_ACCOUNT_ID, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -181,7 +207,8 @@ void removeBySessionIdRemovesValueAndSetMembership() { verify(redisTemplate).delete("gameplaypresence:session:3"); verify(setOperations).remove("gameplaypresence:22:7:sessions", "3"); - verify(setOperations).remove("gameplaypresence:22:account:102:sessions", "3"); + verify(setOperations) + .remove("gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions", "3"); } @Test @@ -194,7 +221,7 @@ void findConnectedBySessionIdReadsPresenceRecordDirectly() { 7L, "demo", "production", - "2", + OTHER_ACCOUNT_ID, 102L, "Ben", GameplayPresenceRole.PLAYER, @@ -221,7 +248,7 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest 7L, "demo", "production", - "102", + PLAYER_ACCOUNT_ID, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -249,7 +276,8 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest == null), org.mockito.Mockito.eq(TTL)); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); - verify(redisTemplate).expire("gameplaypresence:22:account:102:sessions", TTL); + verify(redisTemplate) + .expire("gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions", TTL); } @Test @@ -264,7 +292,7 @@ void setExplicitAfkRefreshesPresenceRecord() { 7L, "demo", "production", - "102", + PLAYER_ACCOUNT_ID, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -289,12 +317,13 @@ void setExplicitAfkRefreshesPresenceRecord() { .explicitAfkSinceEpochMs())), org.mockito.Mockito.eq(TTL)); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); - verify(redisTemplate).expire("gameplaypresence:22:account:102:sessions", TTL); + verify(redisTemplate) + .expire("gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions", TTL); } @Test void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { - when(setOperations.members("gameplaypresence:22:account:102:sessions")) + when(setOperations.members("gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions")) .thenReturn(new LinkedHashSet<>(List.of("3", "4"))); when(valueOperations.get("gameplaypresence:session:3")) .thenReturn( @@ -306,7 +335,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { "demo", "production", 17L, - "102", + PLAYER_ACCOUNT_ID, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -324,7 +353,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { "demo", "production", 17L, - "102", + PLAYER_ACCOUNT_ID, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -333,18 +362,74 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { 110L, 120L)); - var result = service.listConnectedByAccountIds(22L, List.of("102")); + var result = service.listConnectedByAccountIds(22L, List.of(PLAYER_ACCOUNT_ID)); assertEquals(1, result.size()); - assertEquals(2, result.get("102").size()); - assertEquals(4L, result.get("102").get(0).sessionId()); - assertEquals(3L, result.get("102").get(1).sessionId()); + assertEquals(2, result.get(PLAYER_ACCOUNT_ID).size()); + assertEquals(4L, result.get(PLAYER_ACCOUNT_ID).get(0).sessionId()); + assertEquals(3L, result.get(PLAYER_ACCOUNT_ID).get(1).sessionId()); } @Test - void listConnectedByAccountIdsUsesOpaqueAccountTextForIndexAndResultKey() { - String accountId = "account-uuid-opaque-v1"; - String accountIndexKey = "gameplaypresence:22:account:account-uuid-opaque-v1:sessions"; + void listConnectedByAccountIdsDoesNotAdmitAnotherAccountPresence() { + String accountIndexKey = "gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions"; + when(setOperations.members(accountIndexKey)).thenReturn(new LinkedHashSet<>(List.of("5"))); + when(valueOperations.get("gameplaypresence:session:5")) + .thenReturn( + new net.firedevops.firemud.gamesession.service.GameplayPresence( + 5L, + 22L, + 7L, + "SHARED", + "demo", + "production", + 17L, + OTHER_ACCOUNT_ID, + 202L, + "Ben", + GameplayPresenceRole.PLAYER, + 90L, + null, + 110L, + 120L)); + + assertEquals(Map.of(), service.listConnectedByAccountIds(22L, List.of(PLAYER_ACCOUNT_ID))); + + verify(setOperations).remove(accountIndexKey, "5"); + } + + @Test + void listConnectedByAccountIdsRetainsReadableLegacyNumericAccountCarrier() { + String accountIndexKey = "gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions"; + when(setOperations.members(accountIndexKey)).thenReturn(new LinkedHashSet<>(List.of("5"))); + when(valueOperations.get("gameplaypresence:session:5")) + .thenReturn( + new net.firedevops.firemud.gamesession.service.GameplayPresence( + 5L, + 22L, + 7L, + "SHARED", + "demo", + "production", + 17L, + "102", + 202L, + "Ben", + GameplayPresenceRole.PLAYER, + 90L, + null, + 110L, + 120L)); + + assertEquals(Map.of(), service.listConnectedByAccountIds(22L, List.of(PLAYER_ACCOUNT_ID))); + + verify(setOperations, Mockito.never()).remove(accountIndexKey, "5"); + } + + @Test + void listConnectedByAccountIdsUsesCanonicalAccountUuidForIndexAndResultKey() { + String accountId = OTHER_ACCOUNT_ID; + String accountIndexKey = "gameplaypresence:22:account:" + accountId + ":sessions"; String presenceKey = "gameplaypresence:session:9"; var presence = new net.firedevops.firemud.gamesession.service.GameplayPresence( @@ -375,7 +460,7 @@ void listConnectedByAccountIdsUsesOpaqueAccountTextForIndexAndResultKey() { @Test void listConnectedByAccountIdsPrunesMalformedSessionIndexEntry() { - when(setOperations.members("gameplaypresence:22:account:102:sessions")) + when(setOperations.members("gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions")) .thenReturn(new LinkedHashSet<>(List.of("bad-session", "4"))); when(valueOperations.get("gameplaypresence:session:4")) .thenReturn( @@ -387,7 +472,7 @@ void listConnectedByAccountIdsPrunesMalformedSessionIndexEntry() { "demo", "production", 17L, - "102", + PLAYER_ACCOUNT_ID, 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -396,23 +481,24 @@ void listConnectedByAccountIdsPrunesMalformedSessionIndexEntry() { 110L, 120L)); - var result = service.listConnectedByAccountIds(22L, List.of("102")); + var result = service.listConnectedByAccountIds(22L, List.of(PLAYER_ACCOUNT_ID)); assertEquals(1, result.size()); - assertEquals(1, result.get("102").size()); - assertEquals(4L, result.get("102").get(0).sessionId()); - verify(setOperations).remove("gameplaypresence:22:account:102:sessions", "bad-session"); + assertEquals(1, result.get(PLAYER_ACCOUNT_ID).size()); + assertEquals(4L, result.get(PLAYER_ACCOUNT_ID).get(0).sessionId()); + verify(setOperations) + .remove("gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions", "bad-session"); } @Test void unreadablePresenceIsNotReturnedOrPrunedFromIndexesDuringFailureCleanup() { String presenceKey = "gameplaypresence:session:3"; - String accountIndexKey = "gameplaypresence:22:account:102:sessions"; + String accountIndexKey = "gameplaypresence:22:account:" + PLAYER_ACCOUNT_ID + ":sessions"; when(setOperations.members(accountIndexKey)).thenReturn(new LinkedHashSet<>(List.of("3"))); when(valueOperations.get(presenceKey)) .thenThrow(new SerializationException("old GameplayPresence record shape")); - assertEquals(Map.of(), service.listConnectedByAccountIds(22L, List.of("102"))); + assertEquals(Map.of(), service.listConnectedByAccountIds(22L, List.of(PLAYER_ACCOUNT_ID))); assertEquals(java.util.Optional.empty(), service.findConnectedBySessionId(3L)); assertThrows(IllegalStateException.class, () -> service.removeBySessionId(3L)); @@ -467,7 +553,8 @@ void registerConnectedRejectsUnreadableAndWrongTypePresenceBeforeWriting() { .thenThrow(new SerializationException("old GameplayPresence record shape")) .thenReturn("incompatible retained presence"); SessionContext context = - new SessionContext(3L, 22L, "102", "player@example.com", 202L, "Ben", 7L, "R-1", null); + new SessionContext( + 3L, 22L, PLAYER_ACCOUNT_ID, "player@example.com", 202L, "Ben", 7L, "R-1", null); assertThrows(IllegalStateException.class, () -> service.registerConnected(context)); assertThrows(IllegalStateException.class, () -> service.registerConnected(context)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java index 381ea957b9..76249f8c88 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java @@ -15,6 +15,8 @@ import net.firedevops.firemud.gamesession.service.SessionContextUnavailableException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; @@ -25,6 +27,9 @@ @SuppressWarnings("unchecked") class RedisSessionContextServiceTest { private static final Duration TTL = Duration.ofMillis(1000L); + private static final String ACCOUNT_UUID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + private static final String OTHER_ACCOUNT_UUID = "2b23537d-c5cc-4fa8-8c0d-dc4c38c77a92"; + private static final String THIRD_ACCOUNT_UUID = "f0381e18-4931-4660-9bc4-4a4f73a7ea6d"; private final RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); private final ValueOperations valueOperations = @@ -44,9 +49,41 @@ void setUp() { service = new RedisSessionContextService(redisTemplate, TTL.toMillis()); } + @ParameterizedTest + @ValueSource( + strings = { + "7", + "bad-account", + "00000000-0000-0000-0000-000000000000", + " b8d093f7-cb70-40ed-9fac-3c82d4bf28f1" + }) + void invalidRetainedAccountIdentityCannotBeUsedReplacedOrDeleted(String invalidAccount) { + SessionContext retained = new SessionContext(1L, 10L, invalidAccount, 30L, 40L, "jwt"); + when(valueOperations.get("sessionctx:10:1:context")).thenReturn(retained); + when(valueOperations.get("sessionctx:session:1:context")).thenReturn(retained); + assertThrows(SessionContextUnavailableException.class, () -> service.findBySessionId(1L)); + assertThrows( + SessionContextUnavailableException.class, + () -> service.save(new SessionContext(1L, 10L, ACCOUNT_UUID, 30L, 40L, "new-jwt"))); + assertThrows( + SessionContextUnavailableException.class, () -> service.deleteBySessionId(10L, 1L)); + verify(redisTemplate, never()).multi(); + verify(redisTemplate, never()).delete(Mockito.anyString()); + verify(valueOperations, never()) + .set(Mockito.anyString(), Mockito.any(), Mockito.any(Duration.class)); + } + + @Test + void saveRejectsNumericAccountBeforeAnyRedisMutation() { + assertThrows( + IllegalArgumentException.class, + () -> service.save(new SessionContext(1L, 10L, "7", 30L, 40L, "jwt"))); + verify(redisTemplate, never()).execute(Mockito.any(SessionCallback.class)); + } + @Test void saveStoresContextInSessionAndIdentityKeys() { - SessionContext context = new SessionContext(1L, 10L, "20", 30L, 40L, "jwt"); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_UUID, 30L, 40L, "jwt"); service.save(context); @@ -58,8 +95,8 @@ void saveStoresContextInSessionAndIdentityKeys() { @Test void saveRemovesStaleSessionKeyBeforeWritingNewIdentityBinding() { - SessionContext existing = new SessionContext(1L, 10L, "20", 30L, 40L, "old-jwt"); - SessionContext replacement = new SessionContext(2L, 10L, "20", 30L, 40L, "new-jwt"); + SessionContext existing = new SessionContext(1L, 10L, ACCOUNT_UUID, 30L, 40L, "old-jwt"); + SessionContext replacement = new SessionContext(2L, 10L, ACCOUNT_UUID, 30L, 40L, "new-jwt"); when(valueOperations.get("sessionctx:10:identity:40:30:context")).thenReturn(existing); service.save(replacement); @@ -72,9 +109,11 @@ void saveRemovesStaleSessionKeyBeforeWritingNewIdentityBinding() { @Test void savePreservesForeignTenantIndexesFromSessionAlias() { SessionContext incoming = - new SessionContext(1L, 10L, "88", "new-login", 60L, "Current", 50L, "R-1", "new-jwt"); + new SessionContext( + 1L, 10L, ACCOUNT_UUID, "new-login", 60L, "Current", 50L, "R-1", "new-jwt"); SessionContext foreignTenant = - new SessionContext(1L, 99L, "30", "other-login", 31L, "Foreign", 41L, "R-2", "old-jwt"); + new SessionContext( + 1L, 99L, OTHER_ACCOUNT_UUID, "other-login", 31L, "Foreign", 41L, "R-2", "old-jwt"); when(valueOperations.get("sessionctx:session:1:context")).thenReturn(foreignTenant); service.save(incoming); @@ -93,9 +132,11 @@ void savePreservesForeignTenantIndexesFromSessionAlias() { @Test void savePreservesForeignSessionIndexesFromSessionAlias() { SessionContext incoming = - new SessionContext(1L, 10L, "88", "new-login", 60L, "Current", 50L, "R-1", "new-jwt"); + new SessionContext( + 1L, 10L, ACCOUNT_UUID, "new-login", 60L, "Current", 50L, "R-1", "new-jwt"); SessionContext foreignSession = - new SessionContext(2L, 10L, "30", "other-login", 31L, "Foreign", 41L, "R-2", "old-jwt"); + new SessionContext( + 2L, 10L, OTHER_ACCOUNT_UUID, "other-login", 31L, "Foreign", 41L, "R-2", "old-jwt"); when(valueOperations.get("sessionctx:session:1:context")).thenReturn(foreignSession); service.save(incoming); @@ -114,12 +155,14 @@ void savePreservesForeignSessionIndexesFromSessionAlias() { @Test void saveCleansDistinctSessionAliasIndexesForSameTenantAndSession() { SessionContext incoming = - new SessionContext(1L, 10L, "88", "new-login", 60L, "Current", 50L, "R-1", "new-jwt"); + new SessionContext( + 1L, 10L, ACCOUNT_UUID, "new-login", 60L, "Current", 50L, "R-1", "new-jwt"); SessionContext existingContext = new SessionContext( - 1L, 10L, "30", "context-login", 31L, "ContextOld", 41L, "R-2", "ctx-jwt"); + 1L, 10L, OTHER_ACCOUNT_UUID, "context-login", 31L, "ContextOld", 41L, "R-2", "ctx-jwt"); SessionContext existingSessionAlias = - new SessionContext(1L, 10L, "31", "alias-login", 32L, "AliasOld", 42L, "R-3", "alias-jwt"); + new SessionContext( + 1L, 10L, THIRD_ACCOUNT_UUID, "alias-login", 32L, "AliasOld", 42L, "R-3", "alias-jwt"); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(existingContext); when(valueOperations.get("sessionctx:session:1:context")).thenReturn(existingSessionAlias); @@ -138,7 +181,7 @@ void saveCleansDistinctSessionAliasIndexesForSameTenantAndSession() { @Test void findByTenantAndSessionIdReturnsPersistedContext() { - SessionContext context = new SessionContext(1L, 10L, "20", 30L, 40L, "jwt"); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_UUID, 30L, 40L, "jwt"); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(context); Optional result = service.findByTenantAndSessionId(10L, 1L); @@ -148,7 +191,7 @@ void findByTenantAndSessionIdReturnsPersistedContext() { @Test void findByGameplayIdentityReturnsPersistedContext() { - SessionContext context = new SessionContext(1L, 10L, "20", 30L, 40L, "jwt"); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_UUID, 30L, 40L, "jwt"); when(valueOperations.get("sessionctx:10:identity:40:30:context")).thenReturn(context); Optional result = service.findByGameplayIdentity(10L, 40L, 30L); @@ -170,7 +213,8 @@ void unreadableRetainedContextFailsClosedWithoutTreatingItAsAbsence() { "unreadable retained state must stop cleanup before its evidence can be deleted"); SessionContext reauthenticated = - new SessionContext(2L, 10L, "77", "demo@example.com", 0L, null, 0L, null, "fresh-jwt"); + new SessionContext( + 2L, 10L, ACCOUNT_UUID, "demo@example.com", 0L, null, 0L, null, "fresh-jwt"); service.save(reauthenticated); verify(valueOperations).set("sessionctx:10:2:context", reauthenticated, TTL); @@ -188,7 +232,9 @@ void unreadableSessionAliasIsNotOverwrittenOrDeletedWhenTenantContextIsAbsent() assertThrows(SerializationException.class, () -> service.deleteBySessionId(10L, 1L)); assertThrows( SerializationException.class, - () -> service.save(new SessionContext(1L, 10L, "77", null, 0L, null, 0L, null, null))); + () -> + service.save( + new SessionContext(1L, 10L, ACCOUNT_UUID, null, 0L, null, 0L, null, null))); verify(redisTemplate, never()).multi(); verify(redisTemplate, never()).exec(); @@ -199,7 +245,7 @@ void unreadableSessionAliasIsNotOverwrittenOrDeletedWhenTenantContextIsAbsent() @Test void deleteBySessionIdRemovesBothKeys() { - SessionContext context = new SessionContext(1L, 10L, "20", 30L, 40L, "jwt"); + SessionContext context = new SessionContext(1L, 10L, ACCOUNT_UUID, 30L, 40L, "jwt"); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(context); service.deleteBySessionId(10L, 1L); @@ -212,7 +258,8 @@ void deleteBySessionIdRemovesBothKeys() { @Test void deleteBySessionIdPreservesDifferentTenantAliasIndexes() { - SessionContext differentTenant = new SessionContext(1L, 99L, "30", 31L, 41L, "other-jwt"); + SessionContext differentTenant = + new SessionContext(1L, 99L, OTHER_ACCOUNT_UUID, 31L, 41L, "other-jwt"); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(null); when(valueOperations.get("sessionctx:session:1:context")).thenReturn(differentTenant); @@ -225,8 +272,9 @@ void deleteBySessionIdPreservesDifferentTenantAliasIndexes() { @Test void deleteBySessionIdPreservesDifferentSessionAliasIndexes() { - SessionContext requested = new SessionContext(1L, 10L, "20", 30L, 40L, "requested-jwt"); - SessionContext differentSession = new SessionContext(2L, 10L, "21", 31L, 41L, "other-jwt"); + SessionContext requested = new SessionContext(1L, 10L, ACCOUNT_UUID, 30L, 40L, "requested-jwt"); + SessionContext differentSession = + new SessionContext(2L, 10L, OTHER_ACCOUNT_UUID, 31L, 41L, "other-jwt"); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(requested); when(valueOperations.get("sessionctx:session:1:context")).thenReturn(differentSession); @@ -241,8 +289,8 @@ void deleteBySessionIdPreservesDifferentSessionAliasIndexes() { @Test void deleteBySessionIdCleansDistinctContextForSameTenantAndSession() { - SessionContext requested = new SessionContext(1L, 10L, "20", 30L, 40L, "requested-jwt"); - SessionContext sameOwner = new SessionContext(1L, 10L, "20", 31L, 41L, "other-jwt"); + SessionContext requested = new SessionContext(1L, 10L, ACCOUNT_UUID, 30L, 40L, "requested-jwt"); + SessionContext sameOwner = new SessionContext(1L, 10L, ACCOUNT_UUID, 31L, 41L, "other-jwt"); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(requested); when(valueOperations.get("sessionctx:session:1:context")).thenReturn(sameOwner); @@ -257,7 +305,7 @@ void deleteBySessionIdCleansDistinctContextForSameTenantAndSession() { @Test void savePreservesLocaleTagInStoredContext() { SessionContext context = - new SessionContext(1L, 10L, "20", null, 30L, null, 40L, "R-1", "jwt", "fr", 40L); + new SessionContext(1L, 10L, ACCOUNT_UUID, null, 30L, null, 40L, "R-1", "jwt", "fr", 40L); service.save(context); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/ChatTestFixturesTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/ChatTestFixturesTest.java index c7eb8a0c57..4085511e4a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/ChatTestFixturesTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/ChatTestFixturesTest.java @@ -2,20 +2,24 @@ import static org.assertj.core.api.Assertions.assertThat; +import net.firedevops.firemud.test.AccountRuntimeStubServer; import org.junit.jupiter.api.Test; class ChatTestFixturesTest { @Test - void rosterAndRoomViewsRetainThePublishedNumericFixtureBindings() { + void rosterAndRoomViewsRetainDistinctAccountAndCharacterFixtureBindings() { assertThat(ChatTestFixtures.EMBERLINE_ACCOUNT_ROW_ID).isEqualTo(7L); assertThat(ChatTestFixtures.SORA_ACCOUNT_ROW_ID).isEqualTo(8L); assertThat(ChatTestFixtures.NYX_ACCOUNT_ROW_ID).isEqualTo(9L); assertThat(ChatTestFixtures.EMBERLINE_CHARACTER_ID).isEqualTo(7L); assertThat(ChatTestFixtures.SORA_CHARACTER_ID).isEqualTo(8L); assertThat(ChatTestFixtures.NYX_CHARACTER_ID).isEqualTo(9L); - assertThat(ChatTestFixtures.characterByName("Emberline").getAccountId()).isEqualTo("7"); - assertThat(ChatTestFixtures.characterByName("Sora").getAccountId()).isEqualTo("8"); - assertThat(ChatTestFixtures.characterByName("Nyx").getAccountId()).isEqualTo("9"); + assertThat(ChatTestFixtures.characterByName("Emberline").getAccountId()) + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(7L)); + assertThat(ChatTestFixtures.characterByName("Sora").getAccountId()) + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(8L)); + assertThat(ChatTestFixtures.characterByName("Nyx").getAccountId()) + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(9L)); assertThat(ChatTestFixtures.sampleEntities().getEntitiesList()) .extracting(entity -> entity.getEntityId()) .containsExactly("7", "8", "9", "NPC-001"); @@ -29,7 +33,8 @@ void recipientSessionUsesTheSameSubjectAsTheCharacterRosterAndRoomView() { assertThat(context.sessionId()).isEqualTo(90210L); assertThat(context.tenantId()).isEqualTo(1L); - assertThat(context.accountId()).isEqualTo("8"); + assertThat(context.accountId()) + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(8L)); assertThat(context.accountId()).isEqualTo(character.getAccountId()); assertThat(context.characterId()).isEqualTo(8L); assertThat(Long.toString(context.characterId())).isEqualTo(character.getId()); @@ -47,11 +52,16 @@ void recipientSessionUsesTheSameSubjectAsTheCharacterRosterAndRoomView() { @Test void scenarioOverridesDoNotChangeTheNextRosterOrRecipient() { var changed = - ChatTestFixtures.characterByName("Sora").toBuilder().setAccountId("81").setId("82").build(); + ChatTestFixtures.characterByName("Sora").toBuilder() + .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(81L)) + .setId("82") + .build(); - assertThat(changed.getAccountId()).isEqualTo("81"); + assertThat(changed.getAccountId()) + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(81L)); assertThat(changed.getId()).isEqualTo("82"); - assertThat(ChatTestFixtures.characterByName("Sora").getAccountId()).isEqualTo("8"); + assertThat(ChatTestFixtures.characterByName("Sora").getAccountId()) + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(8L)); assertThat(ChatTestFixtures.characterByName("Sora").getId()).isEqualTo("8"); assertThat(ChatTestFixtures.soraRecipientSession(90210L, 1L, 3L).characterId()).isEqualTo(8L); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/GameplayCommandTestFixturesTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/GameplayCommandTestFixturesTest.java index 9d1546f803..4f8bae8cf5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/GameplayCommandTestFixturesTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/GameplayCommandTestFixturesTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import net.firedevops.firemud.gamesession.service.SessionContext; +import net.firedevops.firemud.test.AccountRuntimeStubServer; import org.junit.jupiter.api.Test; class GameplayCommandTestFixturesTest { @@ -12,7 +13,8 @@ void inventoryScenarioRetainsItsIndependentSubjectAndRuntimeTarget() { assertThat(context.sessionId()).isEqualTo(1L); assertThat(context.tenantId()).isEqualTo(22L); - assertThat(context.accountId()).isEqualTo("123"); + assertThat(context.accountId()) + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(123L)); assertThat(context.characterId()).isEqualTo(911L); assertThat(context.gameInstanceId()).isEqualTo(77L); assertThat(context.roomInstanceId()).isEqualTo("R-7"); @@ -24,10 +26,12 @@ void authoredDispatchAndHistoryKeepTheirDistinctSubjects() { SessionContext dispatch = GameplayCommandTestFixtures.authoredDispatchEmberline(); SessionContext history = GameplayCommandTestFixtures.historyEmberline(); - assertThat(dispatch.accountId()).isEqualTo("41"); + assertThat(dispatch.accountId()) + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(41L)); assertThat(dispatch.sessionId()).isEqualTo(7L); assertThat(dispatch.tenantId()).isEqualTo(22L); - assertThat(history.accountId()).isEqualTo("99"); + assertThat(history.accountId()) + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(99L)); assertThat(history.sessionId()).isEqualTo(22L); assertThat(history.tenantId()).isEqualTo(7L); assertThat(dispatch.characterId()).isEqualTo(7001L); @@ -41,12 +45,15 @@ void durableCommandAndLiveContextShareTheExactActorBinding() { SessionContext context = GameplayCommandTestFixtures.durableDemo(); var command = GameplayCommandTestFixtures.durableDemoCommand("MOVE", "north"); - assertThat(context.accountId()).isEqualTo("7"); + assertThat(context.accountId()) + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(7L)); assertThat(context.characterId()).isEqualTo(91L); assertThat(context.sessionId()).isEqualTo(42L); assertThat(context.tenantId()).isEqualTo(22L); assertThat(context.gameInstanceId()).isEqualTo(5L); assertThat(command.getCharacterId()).isEqualTo(context.characterId()); + assertThat(command.getAccountUuid().toString()).isEqualTo(context.accountId()); + assertThat(command.getAccountId()).isNull(); assertThat(command.getSessionId()).isEqualTo(context.sessionId()); assertThat(command.getTenantId()).isEqualTo(context.tenantId()); assertThat(command.getGameInstanceId()).isEqualTo(context.gameInstanceId()); @@ -98,10 +105,12 @@ void communicationTargetsAndBootstrapContextsKeepTheirOriginalShapes() { SessionContext browse = GameplayCommandTestFixtures.worldBrowseDemo(); SessionContext played = GameplayCommandTestFixtures.webSocketEmberline(); - assertThat(sender.accountId()).isEqualTo("123"); + assertThat(sender.accountId()) + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(123L)); assertThat(sender.characterId()).isEqualTo(123L); assertThat(sender.roomInstanceId()).isEqualTo("R-1"); - assertThat(target.accountId()).isEqualTo("456"); + assertThat(target.accountId()) + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(456L)); assertThat(target.characterId()).isEqualTo(456L); assertThat(target.roomInstanceId()).isEqualTo("R-2"); assertThat(target.localeTag()).isEqualTo("en-NZ"); @@ -133,7 +142,8 @@ void whoAndActivitySubjectsKeepDistinctSessionAndActorCoordinates() { assertThat(dara.characterId()).isEqualTo(104L); assertThat(dara.jwt()).isEqualTo("moderator-jwt"); assertThat(activity.sessionId()).isEqualTo(1L); - assertThat(activity.accountId()).isEqualTo("2"); + assertThat(activity.accountId()) + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(2L)); assertThat(activity.characterId()).isEqualTo(102L); assertThat(activity.connectedAtEpochMs()).isEqualTo(100L); assertThat(activity.explicitAfkSinceEpochMs()).isEqualTo(300L); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java index 30af581f9c..4c6f5af9d2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java @@ -11,6 +11,7 @@ import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.test.ChatTestFixtures; +import net.firedevops.firemud.test.AccountRuntimeStubServer; import org.junit.jupiter.api.Test; class EntityManagementStubServerTest { @@ -26,9 +27,9 @@ void listsOnlyThePersistedSharedCharacterForTheRequestedTenantAndAccount() throw for (FixtureCharacter fixture : List.of( - new FixtureCharacter("7", "Emberline"), - new FixtureCharacter("8", "Sora"), - new FixtureCharacter("9", "Nyx"))) { + new FixtureCharacter(accountUuid(7L), "Emberline"), + new FixtureCharacter(accountUuid(8L), "Sora"), + new FixtureCharacter(accountUuid(9L), "Nyx"))) { ListCharactersByAccountResponse response = listCharacters( stub, "1", fixture.accountId(), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); @@ -48,14 +49,14 @@ void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { Character.newBuilder() .setId("101") .setTenantId("1") - .setAccountId("101") + .setAccountId(accountUuid(101L)) .setName("player-1") .build(); Character secondPlayer = Character.newBuilder() .setId("102") .setTenantId("1") - .setAccountId("102") + .setAccountId(accountUuid(102L)) .setName("player-2") .build(); @@ -68,15 +69,27 @@ void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { EntityManagementServiceGrpc.newBlockingStub(channel); assertThat( - listCharacters(stub, "1", "101", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, + "1", + accountUuid(101L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .containsExactly(sharedCharacter(firstPlayer)); assertThat( - listCharacters(stub, "1", "102", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, + "1", + accountUuid(102L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .containsExactly(sharedCharacter(secondPlayer)); assertThat( - listCharacters(stub, "2", "101", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, + "2", + accountUuid(101L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); } finally { @@ -95,11 +108,16 @@ void unknownOrMismatchedTenantAndAccountReturnNoCharacters() throws Exception { EntityManagementServiceGrpc.newBlockingStub(channel); assertThat( - listCharacters(stub, "2", "7", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, "2", accountUuid(7L), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); assertThat( - listCharacters(stub, "1", "999", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + listCharacters( + stub, + "1", + accountUuid(999L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); } finally { @@ -118,11 +136,19 @@ void unsupportedPlayableStateScopesReturnNoCharacters() throws Exception { EntityManagementServiceGrpc.newBlockingStub(channel); assertThat( - listCharacters(stub, "1", "7", PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) + listCharacters( + stub, + "1", + accountUuid(7L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) .getCharactersList()) .isEmpty(); assertThat( - listCharacters(stub, "1", "7", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) + listCharacters( + stub, + "1", + accountUuid(7L), + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) .getCharactersList()) .isEmpty(); } finally { @@ -155,5 +181,9 @@ private static Character sharedCharacter(Character character) { .build(); } + private static String accountUuid(long accountRowId) { + return AccountRuntimeStubServer.accountUuidForTestFixture(accountRowId); + } + private record FixtureCharacter(String accountId, String name) {} } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java index 9abd52fb73..20dfa7b809 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java @@ -253,7 +253,7 @@ void genericWebSocketProjectsFriendViewThroughFriendsRenderer() { new FriendPresenceViewOutput.Entry( 1, 77L, - 41L, + "00000000-0000-4000-8000-000000000041", "ONLINE", null, "Sora", @@ -421,7 +421,7 @@ void firstPartyWebProjectsFriendsViewPayloads() throws Exception { new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + "00000000-0000-4000-8000-000000000003", "active", 1_744_336_000_000L, "Sora", @@ -447,7 +447,7 @@ void firstPartyWebProjectsFriendsViewPayloads() throws Exception { new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + "00000000-0000-4000-8000-000000000003", "active", 1_744_336_000_000L, "Sora", @@ -479,8 +479,8 @@ void firstPartyWebProjectsFriendsViewPayloads() throws Exception { .path("friends") .get(0) .path("friendAccountId") - .asLong()) - .isEqualTo(3L); + .asText()) + .isEqualTo("00000000-0000-4000-8000-000000000003"); assertThat( json.path("outputs") .get(0) @@ -548,7 +548,7 @@ void firstPartyWebProjectsFriendDetailViewPayloads() throws Exception { new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + "00000000-0000-4000-8000-000000000003", "active", 1_744_336_000_000L, "Sora", @@ -570,7 +570,7 @@ void firstPartyWebProjectsFriendDetailViewPayloads() throws Exception { new FriendPresenceViewOutput.Entry( 1, 11L, - 3L, + "00000000-0000-4000-8000-000000000003", "active", 1_744_336_000_000L, "Sora", @@ -599,8 +599,8 @@ void firstPartyWebProjectsFriendDetailViewPayloads() throws Exception { .path("payload") .path("friend") .path("friendAccountId") - .asLong()) - .isEqualTo(3L); + .asText()) + .isEqualTo("00000000-0000-4000-8000-000000000003"); assertThat( json.path("outputs") .get(0) @@ -706,7 +706,8 @@ void firstPartyWebProjectsFriendMutationResultPayloads() throws Exception { GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); FriendMutationResultOutput payloadView = - new FriendMutationResultOutput("REMOVE", 77L, "Sora", "Sora", 1); + new FriendMutationResultOutput( + "REMOVE", "00000000-0000-4000-8000-000000000077", "Sora", "Sora", 1); String payload = projector.projectCommandResponse( @@ -724,8 +725,8 @@ void firstPartyWebProjectsFriendMutationResultPayloads() throws Exception { .isEqualTo("friend_mutation_result"); assertThat(json.path("outputs").get(0).path("payload").path("action").asText()) .isEqualTo("REMOVE"); - assertThat(json.path("outputs").get(0).path("payload").path("friendAccountId").asLong()) - .isEqualTo(77L); + assertThat(json.path("outputs").get(0).path("payload").path("friendAccountId").asText()) + .isEqualTo("00000000-0000-4000-8000-000000000077"); assertThat(json.path("outputs").get(0).path("payload").path("displayName").asText()) .isEqualTo("Sora"); assertThat(json.path("outputs").get(0).path("payload").path("ordinal").asInt()).isEqualTo(1); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index b99e790051..c0b23faec5 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -216,7 +216,7 @@ ModerationPolicyClient moderationPolicyClient() { ModerationPolicyClient client = org.mockito.Mockito.mock(ModerationPolicyClient.class); org.mockito.Mockito.when( client.evaluateGameplayAdmission( - org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())) + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java index f50490bd33..512b517470 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/ChatTestFixtures.java @@ -5,6 +5,7 @@ import net.firedevops.firemud.entitymanagement.v1.ListRoomEntitiesResponse; import net.firedevops.firemud.entitymanagement.v1.RoomEntity; import net.firedevops.firemud.gamesession.service.SessionContext; +import net.firedevops.firemud.test.AccountRuntimeStubServer; public final class ChatTestFixtures { public static final String ROOM_ID = "R-1021"; @@ -65,7 +66,8 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_EMBERLINE) .setTenantId("1") - .setAccountId(Long.toString(EMBERLINE_ACCOUNT_ROW_ID)) + .setAccountId( + AccountRuntimeStubServer.accountUuidForTestFixture(EMBERLINE_ACCOUNT_ROW_ID)) .setName("Emberline") .build(); } @@ -73,7 +75,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_SORA) .setTenantId("1") - .setAccountId(Long.toString(SORA_ACCOUNT_ROW_ID)) + .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(SORA_ACCOUNT_ROW_ID)) .setName("Sora") .build(); } @@ -81,7 +83,7 @@ public static Character characterByName(String name) { return Character.newBuilder() .setId(PLAYER_NYX) .setTenantId("1") - .setAccountId(Long.toString(NYX_ACCOUNT_ROW_ID)) + .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(NYX_ACCOUNT_ROW_ID)) .setName("Nyx") .build(); } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/GameplayCommandTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/GameplayCommandTestFixtures.java index 71d2c2ae13..c6fe45d4d3 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/GameplayCommandTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/GameplayCommandTestFixtures.java @@ -2,6 +2,7 @@ import net.firedevops.firemud.gamesession.entity.GameplayCommand; import net.firedevops.firemud.gamesession.service.SessionContext; +import net.firedevops.firemud.test.AccountRuntimeStubServer; /** Named command scenarios shared by handler, dispatch, and durable-execution tests. */ public final class GameplayCommandTestFixtures { @@ -9,27 +10,67 @@ private GameplayCommandTestFixtures() {} public static SessionContext inventoryEmberline() { return new SessionContext( - 1L, 22L, "123", "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); + 1L, + 22L, + AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "emberline@example.com", + 911L, + "Emberline", + 77L, + "R-7", + "jwt-token"); } public static SessionContext authoredDispatchEmberline() { return new SessionContext( - 7L, 22L, "41", "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, + 22L, + AccountRuntimeStubServer.accountUuidForTestFixture(41L), + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); } public static SessionContext historyEmberline() { return new SessionContext( - 22L, 7L, "99", "demo@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 22L, + 7L, + AccountRuntimeStubServer.accountUuidForTestFixture(99L), + "demo@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); } public static SessionContext durableDemo() { return new SessionContext( - 42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + 42L, + 22L, + AccountRuntimeStubServer.accountUuidForTestFixture(7L), + "demo@example.com", + 91L, + "Demo", + 5L, + "R-1", + "jwt-token"); } public static SessionContext authoredHelpEmberline() { return new SessionContext( - 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); + 41L, + 22L, + AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt"); } public static SessionContext helpCapabilityEmberline() { @@ -38,39 +79,103 @@ public static SessionContext helpCapabilityEmberline() { public static SessionContext helpCapabilityEmberline(long sessionId) { return new SessionContext( - sessionId, 22L, "123", "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + sessionId, + 22L, + AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "emberline@example.com", + 7001L, + "Emberline", + 9L, + "R-1", + "jwt"); } public static SessionContext settingsEmber() { - return new SessionContext(1L, 22L, "123", "demo@example.com", 911L, "Ember", 7L, "R-1", null); + return new SessionContext( + 1L, + 22L, + AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "demo@example.com", + 911L, + "Ember", + 7L, + "R-1", + null); } public static SessionContext unnamedOutputActor() { - return new SessionContext(41L, 22L, "123", 123L, 1L, "R-1", "jwt"); + return new SessionContext( + 41L, 22L, AccountRuntimeStubServer.accountUuidForTestFixture(123L), 123L, 1L, "R-1", "jwt"); } public static SessionContext communicationSenderEmberline() { return new SessionContext( - 41L, 22L, "123", "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + 41L, + 22L, + AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt"); } public static SessionContext communicationTargetSora() { return new SessionContext( - 42L, 22L, "456", "friend@example.com", 456L, "Sora", 1L, "R-2", "jwt", "en-NZ", 1L); + 42L, + 22L, + AccountRuntimeStubServer.accountUuidForTestFixture(456L), + "friend@example.com", + 456L, + "Sora", + 1L, + "R-2", + "jwt", + "en-NZ", + 1L); } public static SessionContext worldBrowseDemo() { - return new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt"); + return new SessionContext( + 1L, + 22L, + AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "demo@example.com", + 0L, + null, + 0L, + "jwt"); } public static SessionContext bootstrapDemo() { return new SessionContext( - 41L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 41L, + 22L, + AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "demo@example.com", + 0L, + null, + 0L, + null, + "jwt", + "en-NZ", + 1L); } public static SessionContext webSocketEmberline() { return new SessionContext( - 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + 41L, + 22L, + AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "demo@example.com", + 7001L, + "Emberline", + 7L, + "R-1", + "jwt", + "en-NZ", + 1L); } public static GameplayCommand durableDemoCommand(String commandName, String commandText) { @@ -81,6 +186,7 @@ public static GameplayCommand durableDemoCommand(String commandName, String comm command.setGameInstanceId(actor.gameInstanceId()); command.setSessionId(actor.sessionId()); command.setCharacterId(actor.characterId()); + command.setAccountUuid(java.util.UUID.fromString(actor.accountId())); command.setCommandName(commandName); command.setCommandText(commandText); command.setSanitizedCommandText(commandText); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/GameplayPresenceTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/GameplayPresenceTestFixtures.java index dd21458f23..89947a3fdf 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/GameplayPresenceTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/GameplayPresenceTestFixtures.java @@ -3,25 +3,62 @@ import net.firedevops.firemud.gamesession.service.GameplayPresence; import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; import net.firedevops.firemud.gamesession.service.SessionContext; +import net.firedevops.firemud.test.AccountRuntimeStubServer; /** Concrete WHO roster subjects and the separate activity-resolution scenario. */ public final class GameplayPresenceTestFixtures { private GameplayPresenceTestFixtures() {} public static SessionContext whoBen(String loginName) { - return new SessionContext(2L, 22L, "2", loginName, 102L, "Ben", 7L, "R-1", null); + return new SessionContext( + 2L, + 22L, + AccountRuntimeStubServer.accountUuidForTestFixture(2L), + loginName, + 102L, + "Ben", + 7L, + "R-1", + null); } public static SessionContext whoAster(String loginName, String jwt) { - return new SessionContext(1L, 22L, "1", loginName, 101L, "Aster", 7L, "R-1", jwt); + return new SessionContext( + 1L, + 22L, + AccountRuntimeStubServer.accountUuidForTestFixture(1L), + loginName, + 101L, + "Aster", + 7L, + "R-1", + jwt); } public static SessionContext whoCara() { - return new SessionContext(3L, 22L, "3", "third@example.com", 103L, "Cara", 7L, "R-1", null); + return new SessionContext( + 3L, + 22L, + AccountRuntimeStubServer.accountUuidForTestFixture(3L), + "third@example.com", + 103L, + "Cara", + 7L, + "R-1", + null); } public static SessionContext whoDara(String jwt) { - return new SessionContext(4L, 22L, "4", "moderator@example.com", 104L, "Dara", 7L, "R-1", jwt); + return new SessionContext( + 4L, + 22L, + AccountRuntimeStubServer.accountUuidForTestFixture(4L), + "moderator@example.com", + 104L, + "Dara", + 7L, + "R-1", + jwt); } public static GameplayPresence activityBen( 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 431c62e9e8..94341287c7 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 @@ -1038,7 +1038,7 @@ public void seedLiveSession( new SessionContext( sessionId, tenantId, - Long.toString(accountId), + AccountRuntimeStubServer.accountUuidForTestFixture(accountId), loginName, characterId, characterName, @@ -1065,7 +1065,7 @@ public void seedLiveSession( new SessionContext( sessionId, tenantId, - Long.toString(accountId), + AccountRuntimeStubServer.accountUuidForTestFixture(accountId), loginName, characterId, characterName, diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java index cd9a886fa2..bc9ab4f33e 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java @@ -9,6 +9,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; +import net.firedevops.firemud.test.AccountRuntimeStubServer; /** Shared load-oriented gameplay scenario helpers above the base cross-service stack. */ public final class GameplayLoadScenarios { @@ -73,7 +74,7 @@ public static List seedPlayers( Character.newBuilder() .setId(Long.toString(accountId)) .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(accountId)) .setName(label) .build()); players.add( diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/data/TestDataSeeder.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/data/TestDataSeeder.java index b1b5ed7a11..56bddcc0c8 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/data/TestDataSeeder.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/data/TestDataSeeder.java @@ -4,7 +4,6 @@ import java.time.Instant; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.loggingadmin.entity.LogEvent; -import net.firedevops.firemud.loggingadmin.entity.ModerationAction; import net.firedevops.firemud.loggingadmin.entity.PlayerReport; import net.firedevops.firemud.loggingadmin.repository.LogEventRepository; import net.firedevops.firemud.loggingadmin.repository.ModerationActionRepository; @@ -39,7 +38,8 @@ public class TestDataSeeder implements ApplicationRunner { public void run(ApplicationArguments args) { ensureStartupLogEvent(); ensureSamplePlayerReport(); - ensureSampleModerationAction(); + // Moderation examples require an Account-owned canonical UUID association. + // The legacy numeric demo key is not evidence of that identity. } private void ensureStartupLogEvent() { @@ -72,20 +72,4 @@ private void ensureSamplePlayerReport() { } playerReportRepository.save(report); } - - private void ensureSampleModerationAction() { - ModerationAction action = - moderationActionRepository - .findFirstByTenantIdAndAccountIdAndActionAndReason( - DEMO_TENANT_ID, DEMO_TARGET_ACCOUNT_ID, "warning", "initial seed") - .orElseGet(ModerationAction::new); - action.setTenantId(DEMO_TENANT_ID); - action.setAccountId(DEMO_TARGET_ACCOUNT_ID); - action.setAction("warning"); - action.setReason("initial seed"); - if (action.getCreatedAt() == null) { - action.setCreatedAt(Instant.now()); - } - moderationActionRepository.save(action); - } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ApplyModerationActionRequest.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ApplyModerationActionRequest.java index 05e0e3b9e8..0c901c801e 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ApplyModerationActionRequest.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ApplyModerationActionRequest.java @@ -4,10 +4,15 @@ import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; import jakarta.validation.constraints.Size; +import net.firedevops.firemud.common.security.JwtClaims; public record ApplyModerationActionRequest( @NotNull @Positive Long tenantId, - @NotNull @Positive Long accountId, + @NotBlank String accountId, @NotNull @Positive Long sessionId, @NotBlank @Size(max = 20) String action, - @Size(max = 255) String reason) {} + @Size(max = 255) String reason) { + public ApplyModerationActionRequest { + JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/GameplayCommandStatusDto.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/GameplayCommandStatusDto.java index e6aa84c659..cddd430a8d 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/GameplayCommandStatusDto.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/GameplayCommandStatusDto.java @@ -9,7 +9,7 @@ public record GameplayCommandStatusDto( long tenantId, long gameInstanceId, long sessionId, - Long accountId, + String accountId, Long characterId, String commandName, String sanitizedCommandText, diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ModerationActionDto.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ModerationActionDto.java index 071837b2a6..b160baf01f 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ModerationActionDto.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ModerationActionDto.java @@ -8,7 +8,7 @@ public record ModerationActionDto( Long id, @NotNull Long tenantId, - @NotNull Long accountId, + @NotNull String accountId, @NotBlank @Size(max = 20) String action, @Size(max = 255) String reason, Instant createdAt, diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/ModerationAction.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/ModerationAction.java index 970b601281..83a6009475 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/ModerationAction.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/ModerationAction.java @@ -1,13 +1,14 @@ package net.firedevops.firemud.loggingadmin.entity; import java.time.Instant; +import java.util.UUID; import lombok.Data; @Data public class ModerationAction { private Long id; private Long tenantId; - private Long accountId; + private UUID accountId; private String action; private String reason; private Instant createdAt; diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/ModerationActionRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/ModerationActionRepository.java index 61d2544f42..9b43674998 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/ModerationActionRepository.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/ModerationActionRepository.java @@ -8,6 +8,7 @@ import java.time.Instant; import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.loggingadmin.entity.ModerationAction; import net.firedevops.firemud.loggingadmin.jooq.tables.records.ModerationActionsRecord; import org.jooq.DSLContext; @@ -31,7 +32,7 @@ public long count() { } public Optional findFirstByTenantIdAndAccountIdAndActionAndReason( - Long tenantId, Long accountId, String action, String reason) { + Long tenantId, UUID accountId, String action, String reason) { return dsl.selectFrom(MODERATION_ACTIONS) .where( MODERATION_ACTIONS @@ -46,7 +47,7 @@ public Optional findFirstByTenantIdAndAccountIdAndActionAndRea } public List findActivePolicyActions( - Long tenantId, Long accountId, List actions, Instant now) { + Long tenantId, UUID accountId, List actions, Instant now) { return dsl.selectFrom(MODERATION_ACTIONS) .where( MODERATION_ACTIONS diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/ModerationService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/ModerationService.java index e605242021..26f8dbd40d 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/ModerationService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/ModerationService.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.loggingadmin.service; +import java.util.UUID; import net.firedevops.firemud.loggingadmin.dto.ApplyModerationActionRequest; import net.firedevops.firemud.loggingadmin.dto.ModerationActionDto; import net.firedevops.firemud.loggingadmin.dto.ModerationPolicyDecisionDto; @@ -7,5 +8,5 @@ public interface ModerationService { ModerationActionDto applyAction(ApplyModerationActionRequest request); - ModerationPolicyDecisionDto evaluatePolicy(long tenantId, long accountId, String scope); + ModerationPolicyDecisionDto evaluatePolicy(long tenantId, UUID accountId, String scope); } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/GameplayCommandStatusServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/GameplayCommandStatusServiceImpl.java index e933e93494..eab446aaaf 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/GameplayCommandStatusServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/GameplayCommandStatusServiceImpl.java @@ -3,6 +3,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.micrometer.core.annotation.Timed; import java.time.Instant; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamesession.v1.GameplayCommandStatus; import net.firedevops.firemud.gamesession.v1.GetGameplayCommandStatusResponse; @@ -64,7 +65,7 @@ private GameplayCommandStatusDto toDto(GameplayCommandStatus command) { parseLong(command.getTenantId(), "tenant_id"), parseLong(command.getGameInstanceId(), "game_instance_id"), parseLong(command.getSessionId(), "session_id"), - parseOptionalLong(command.getAccountId(), "account_id"), + parseOptionalAccountUuid(command.getAccountId()), parseOptionalLong(command.getCharacterId(), "character_id"), command.getCommandName(), command.getSanitizedCommandText(), @@ -195,6 +196,18 @@ private void requireNoError(ErrorDetail error) { error.getMessage()); } + private String parseOptionalAccountUuid(String value) { + if (value == null || value.isEmpty()) { + return null; + } + try { + return JwtClaims.requireCanonicalAccountUuid(value, "account_id"); + } catch (IllegalArgumentException ex) { + throw new ResponseStatusException( + HttpStatus.INTERNAL_SERVER_ERROR, "control-plane account_id was invalid"); + } + } + private long parseLong(String value, String field) { return ControlPlaneResponseReaders.parseLong(value, field); } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java index 7372b2d659..7fe45e1381 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java @@ -7,9 +7,11 @@ import io.micrometer.core.instrument.MeterRegistry; import java.util.List; import java.util.Set; +import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; +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.loggingadmin.service.LogEventService; @@ -189,7 +191,7 @@ public void applyModerationAction( try { AdminRoleGuard.requireAdminRole(); RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"); - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"); + JwtClaims.requireCanonicalAccountUuid(request.getAccountId(), "accountId"); RequestIdValidation.requirePositiveLong(request.getSessionId(), "sessionId"); ApplyModerationActionResponse response = ApplyModerationActionResponse.newBuilder() @@ -253,7 +255,8 @@ public void evaluateModerationPolicy( var decision = moderationService.evaluatePolicy( RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"), + UUID.fromString( + JwtClaims.requireCanonicalAccountUuid(request.getAccountId(), "accountId")), request.getScope()); EvaluateModerationPolicyResponse.Builder response = EvaluateModerationPolicyResponse.newBuilder() diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java index 1bf0431092..255b2acc4e 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java @@ -5,7 +5,9 @@ import java.time.Instant; import java.util.List; import java.util.Locale; +import java.util.UUID; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.loggingadmin.dto.ApplyModerationActionRequest; import net.firedevops.firemud.loggingadmin.dto.ModerationActionDto; import net.firedevops.firemud.loggingadmin.dto.ModerationPolicyDecisionDto; @@ -45,7 +47,7 @@ public ModerationActionDto applyAction(ApplyModerationActionRequest request) { "Applying moderation action {} to account {}", request.action(), request.accountId()); ModerationAction entity = new ModerationAction(); entity.setTenantId(request.tenantId()); - entity.setAccountId(request.accountId()); + entity.setAccountId(UUID.fromString(request.accountId())); entity.setAction(request.action()); entity.setReason(request.reason()); entity.setCreatedAt(Instant.now()); @@ -54,7 +56,9 @@ public ModerationActionDto applyAction(ApplyModerationActionRequest request) { @Override @Timed(value = "moderation.evaluatePolicy") - public ModerationPolicyDecisionDto evaluatePolicy(long tenantId, long accountId, String scope) { + public ModerationPolicyDecisionDto evaluatePolicy(long tenantId, UUID accountId, String scope) { + JwtClaims.requireCanonicalAccountUuid( + accountId == null ? null : accountId.toString(), "accountId"); List blockingActions = blockingActionsFor(scope); if (blockingActions.isEmpty()) { throw new IllegalArgumentException("Unknown moderation policy scope: " + scope); diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcService.java index 1be828872d..7bce1e3465 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcService.java @@ -6,6 +6,7 @@ import io.micrometer.core.instrument.MeterRegistry; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.security.AdminAuthorizationException; +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.loggingadmin.v1.CreateReportRequest; @@ -38,9 +39,10 @@ public void createReport( try { requireSocialGroupsInternalService(); RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"); - RequestIdValidation.requirePositiveLong(request.getReporterAccountId(), "reporterAccountId"); - RequestIdValidation.parseOptionalPositiveLong( - request.getTargetAccountId(), "targetAccountId"); + JwtClaims.requireCanonicalAccountUuid(request.getReporterAccountId(), "reporterAccountId"); + if (!request.getTargetAccountId().isEmpty()) { + JwtClaims.requireCanonicalAccountUuid(request.getTargetAccountId(), "targetAccountId"); + } CreateReportResponse response = CreateReportResponse.newBuilder() .setError( diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/SessionActorReaders.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/SessionActorReaders.java index 09d353edb4..1241c8dba0 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/SessionActorReaders.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/SessionActorReaders.java @@ -8,13 +8,13 @@ final class SessionActorReaders { private SessionActorReaders() {} static String actorPrincipalOrInternalService() { - Long accountId = currentAccountIdOrNull(); - return accountId == null ? "internal-service" : Long.toString(accountId); + String accountUuid = currentAccountUuidOrNull(); + return accountUuid == null ? "internal-service" : accountUuid; } - static Long currentAccountIdOrNull() { + static String currentAccountUuidOrNull() { try { - return SessionContext.currentAccountIdOrNull(); + return SessionContext.currentAccountUuidOrNull(); } catch (IllegalArgumentException ex) { throw new ResponseStatusException( HttpStatus.BAD_REQUEST, "current account claim was invalid"); diff --git a/services/logging-admin-service/src/main/resources/db/migration/V5__moderation_account_uuid.sql b/services/logging-admin-service/src/main/resources/db/migration/V5__moderation_account_uuid.sql new file mode 100644 index 0000000000..9ae5a516bd --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V5__moderation_account_uuid.sql @@ -0,0 +1,18 @@ +-- Existing numeric Account references have no service-local canonical UUID mapping. +-- Deployment is blocked while any legacy moderation row exists. No row is deleted or mapped. +-- [jooq ignore start] +LOCK TABLE moderation_actions IN ACCESS EXCLUSIVE MODE -- [jooq ignore stop] +; +-- [jooq ignore start] +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM moderation_actions) THEN + RAISE EXCEPTION 'Cannot migrate populated legacy moderation Account references without canonical Account identity disposition'; + END IF; +END $$; +-- [jooq ignore stop] +ALTER TABLE moderation_actions ALTER COLUMN account_id TYPE UUID -- [jooq ignore start] +USING NULL::UUID -- [jooq ignore stop] +; +ALTER TABLE moderation_actions ADD CONSTRAINT moderation_actions_account_id_non_nil + CHECK (account_id <> '00000000-0000-0000-0000-000000000000'::UUID); diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java new file mode 100644 index 0000000000..bd17c82a19 --- /dev/null +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.loggingadmin; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +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) +@SuppressWarnings("resource") +class ModerationAccountUuidMigrationPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private DriverManagerDataSource dataSource; + private JdbcTemplate jdbc; + + @BeforeEach + void legacySchema() { + dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Flyway.configure().dataSource(dataSource).cleanDisabled(false).load().clean(); + flyway("4").migrate(); + jdbc = new JdbcTemplate(dataSource); + } + + @Test + void emptySchemaMigratesAndKeepsExactUuidWithoutChangingPolicyFields() { + flyway("5").migrate(); + String account = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + jdbc.update( + "INSERT INTO moderation_actions (tenant_id, account_id, action, reason) VALUES (1, ?::uuid, 'chat_mute', 'abuse')", + account); + assertThat(jdbc.queryForObject("SELECT account_id::text FROM moderation_actions", String.class)) + .isEqualTo(account); + assertThat( + jdbc.queryForObject( + "SELECT action || ':' || reason FROM moderation_actions", String.class)) + .isEqualTo("chat_mute:abuse"); + assertThatThrownBy( + () -> + jdbc.update( + "INSERT INTO moderation_actions (tenant_id, account_id, action) VALUES (1, '00000000-0000-0000-0000-000000000000', 'ban')")) + .hasMessageContaining("moderation_actions_account_id_non_nil"); + } + + @Test + void populatedLegacyRowsBlockMigrationWithoutChangingRowsOrMigrationHistory() { + jdbc.update( + "INSERT INTO moderation_actions (tenant_id, account_id, action, reason) VALUES (1, 9007199254740993, 'ban', 'retain exactly')"); + String before = + jdbc.queryForObject( + "SELECT md5(row_to_json(m)::text) FROM moderation_actions m", String.class); + String history = + jdbc.queryForObject( + "SELECT md5(string_agg(row_to_json(h)::text, ',' ORDER BY installed_rank)) FROM flyway_schema_history h", + String.class); + assertThatThrownBy(() -> flyway("5").migrate()) + .hasStackTraceContaining("Cannot migrate populated legacy moderation Account references"); + assertThat( + jdbc.queryForObject( + "SELECT md5(row_to_json(m)::text) FROM moderation_actions m", String.class)) + .isEqualTo(before); + assertThat( + jdbc.queryForObject( + "SELECT md5(string_agg(row_to_json(h)::text, ',' ORDER BY installed_rank)) FROM flyway_schema_history h", + String.class)) + .isEqualTo(history); + assertThat( + jdbc.queryForObject( + "SELECT data_type FROM information_schema.columns WHERE table_name = 'moderation_actions' AND column_name = 'account_id'", + String.class)) + .isEqualTo("bigint"); + } + + private Flyway flyway(String target) { + return Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .placeholders(Map.of("serviceSchema", "public")) + .target(MigrationVersion.fromVersion(target)) + .load(); + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java index c414923672..212f29fbd6 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java @@ -50,7 +50,8 @@ void clear() { @Test void applyRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Exception { - ApplyModerationActionRequest req = new ApplyModerationActionRequest(1L, 2L, 9L, "ban", ""); + ApplyModerationActionRequest req = + new ApplyModerationActionRequest(1L, "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", 9L, "ban", ""); String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); mockMvc @@ -72,7 +73,8 @@ void applyRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Excepti @Test void applyRejectsCrossTenantScopedAdmin() throws Exception { - ApplyModerationActionRequest req = new ApplyModerationActionRequest(1L, 2L, 9L, "ban", ""); + ApplyModerationActionRequest req = + new ApplyModerationActionRequest(1L, "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", 9L, "ban", ""); String token = jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("moderator")))); @@ -87,7 +89,8 @@ void applyRejectsCrossTenantScopedAdmin() throws Exception { @Test void applyRejectsZeroSessionIdBeforeDispatch() throws Exception { - ApplyModerationActionRequest req = new ApplyModerationActionRequest(1L, 2L, 0L, "ban", ""); + ApplyModerationActionRequest req = + new ApplyModerationActionRequest(1L, "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", 0L, "ban", ""); String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); mockMvc diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/data/TestDataSeederTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/data/TestDataSeederTest.java index 711431faf8..76824c5e8f 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/data/TestDataSeederTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/data/TestDataSeederTest.java @@ -36,15 +36,12 @@ void runSeedsCanonicalRowsWhenMissing() throws Exception { when(playerReportRepository.findFirstByTenantIdAndReporterAccountIdAndTargetAccountIdAndType( 1L, 1L, 2L, "bug")) .thenReturn(Optional.empty()); - when(moderationActionRepository.findFirstByTenantIdAndAccountIdAndActionAndReason( - 1L, 2L, "warning", "initial seed")) - .thenReturn(Optional.empty()); seeder.run(new DefaultApplicationArguments(new String[] {})); verify(logEventRepository).save(any()); verify(playerReportRepository).save(any()); - verify(moderationActionRepository).save(any()); + org.mockito.Mockito.verifyNoInteractions(moderationActionRepository); } @Test @@ -54,15 +51,12 @@ void runReassertsCanonicalRowsWhenTheyAlreadyExist() throws Exception { when(playerReportRepository.findFirstByTenantIdAndReporterAccountIdAndTargetAccountIdAndType( 1L, 1L, 2L, "bug")) .thenReturn(Optional.of(new net.firedevops.firemud.loggingadmin.entity.PlayerReport())); - when(moderationActionRepository.findFirstByTenantIdAndAccountIdAndActionAndReason( - 1L, 2L, "warning", "initial seed")) - .thenReturn(Optional.of(new net.firedevops.firemud.loggingadmin.entity.ModerationAction())); seeder.run(new DefaultApplicationArguments(new String[] {})); verify(logEventRepository).save(any()); verify(playerReportRepository).save(any()); - verify(moderationActionRepository).save(any()); + org.mockito.Mockito.verifyNoInteractions(moderationActionRepository); verify(logEventRepository, never()).count(); verify(playerReportRepository, never()).count(); verify(moderationActionRepository, never()).count(); diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountUuidReceiverTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountUuidReceiverTest.java new file mode 100644 index 0000000000..ab4824804c --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountUuidReceiverTest.java @@ -0,0 +1,150 @@ +package net.firedevops.firemud.loggingadmin.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.dto.ModerationPolicyDecisionDto; +import net.firedevops.firemud.loggingadmin.service.LogEventService; +import net.firedevops.firemud.loggingadmin.service.LogQueryService; +import net.firedevops.firemud.loggingadmin.service.ModerationService; +import net.firedevops.firemud.loggingadmin.v1.CreateReportRequest; +import net.firedevops.firemud.loggingadmin.v1.CreateReportResponse; +import net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyRequest; +import net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mockito; +import org.springframework.web.server.ResponseStatusException; + +class AccountUuidReceiverTest { + private static final String ACCOUNT = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + private static final String ACTOR = "e830a76a-a786-43de-9416-5840fa6e0578"; + + @AfterEach + void clear() { + SessionContext.clear(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "2", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "B8D093F7-CB70-40ED-9FAC-3C82D4BF28F1", + " b8d093f7-cb70-40ed-9fac-3c82d4bf28f1 " + }) + void rejectsInvalidAccountShapesBeforeModerationOrActorUse(String account) { + SessionContext.setContext(ACTOR, List.of(), Map.of(), true, "game-session-service", "peer"); + ModerationService moderation = Mockito.mock(ModerationService.class); + LoggingAdminGrpcService service = + new LoggingAdminGrpcService( + Mockito.mock(LogQueryService.class), + Mockito.mock(LogEventService.class), + moderation, + new SimpleMeterRegistry()); + AtomicReference response = new AtomicReference<>(); + service.evaluateModerationPolicy( + EvaluateModerationPolicyRequest.newBuilder() + .setTenantId("1") + .setAccountId(account) + .setScope("CHAT_SEND") + .build(), + observer(response)); + assertThat(response.get().getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + verifyNoInteractions(moderation); + SessionContext.setContext(account, List.of("platformAdmin"), Map.of()); + assertThatThrownBy(SessionActorReaders::actorPrincipalOrInternalService) + .isInstanceOf(ResponseStatusException.class); + } + + @Test + void moderationLooksUpExactTargetAndPreservesBanWithDistinctCallerAccount() { + SessionContext.setContext(ACTOR, List.of(), Map.of(), true, "game-session-service", "peer"); + ModerationService moderation = Mockito.mock(ModerationService.class); + Instant expires = Instant.ofEpochSecond(1900000000L); + when(moderation.evaluatePolicy(1L, UUID.fromString(ACCOUNT), "CHAT_SEND")) + .thenReturn(new ModerationPolicyDecisionDto(false, "chat_mute", "abuse", expires)); + LoggingAdminGrpcService service = + new LoggingAdminGrpcService( + Mockito.mock(LogQueryService.class), + Mockito.mock(LogEventService.class), + moderation, + new SimpleMeterRegistry()); + AtomicReference response = new AtomicReference<>(); + service.evaluateModerationPolicy( + EvaluateModerationPolicyRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT) + .setScope("CHAT_SEND") + .build(), + observer(response)); + assertThat(response.get().hasError()).isFalse(); + assertThat(response.get().getAllowed()).isFalse(); + assertThat(response.get().getAction()).isEqualTo("chat_mute"); + assertThat(response.get().getReason()).isEqualTo("abuse"); + assertThat(response.get().getExpiresAtEpochSeconds()).isEqualTo(expires.getEpochSecond()); + verify(moderation).evaluatePolicy(1L, UUID.fromString(ACCOUNT), "CHAT_SEND"); + } + + @ParameterizedTest + @ValueSource( + strings = { + "2", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "B8D093F7-CB70-40ED-9FAC-3C82D4BF28F1", + " b8d093f7-cb70-40ed-9fac-3c82d4bf28f1 " + }) + void reportsValidateReporterAndTargetSeparatelyWhilePreservingHold(String invalid) { + SessionContext.setContext(ACTOR, List.of(), Map.of(), true, "social-groups-service", "peer"); + ReportGrpcService service = new ReportGrpcService(new SimpleMeterRegistry()); + for (boolean invalidReporter : List.of(true, false)) { + AtomicReference response = new AtomicReference<>(); + service.createReport( + CreateReportRequest.newBuilder() + .setTenantId("1") + .setReporterAccountId(invalidReporter ? invalid : ACTOR) + .setTargetAccountId(invalidReporter ? ACCOUNT : invalid) + .build(), + observer(response)); + assertThat(response.get().getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + } + AtomicReference held = new AtomicReference<>(); + service.createReport( + CreateReportRequest.newBuilder() + .setTenantId("1") + .setReporterAccountId(ACTOR) + .setTargetAccountId(ACCOUNT) + .build(), + observer(held)); + assertThat(held.get().getError().getCode()).isEqualTo("UNAVAILABLE"); + } + + private static StreamObserver observer(AtomicReference result) { + return new StreamObserver<>() { + public void onNext(T value) { + result.set(value); + } + + public void onError(Throwable error) { + throw new AssertionError(error); + } + + public void onCompleted() {} + }; + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java index 1da50d55ab..9c03c0067f 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java @@ -44,6 +44,8 @@ import org.springframework.web.server.ResponseStatusException; class AdmissionPointerServiceImplTest { + private static final String ACCOUNT_UUID = "11111111-1111-1111-1111-111111111111"; + @Mock private GameSessionControlPlaneClient gameSessionControlPlaneClient; @InjectMocks private AdmissionPointerServiceImpl service; @@ -271,7 +273,7 @@ void listPointerAuditRejectsMismatchedControlPlaneTenant() { @Test void setPointerUsesSessionAccountIdAsActorPrincipal() { - SessionContext.setContext("42", List.of("platformAdmin"), Map.of()); + SessionContext.setContext(ACCOUNT_UUID, List.of("platformAdmin"), Map.of()); when(gameSessionControlPlaneClient.setAdmissionPointer(any())) .thenReturn( SetAdmissionPointerResponse.newBuilder() @@ -304,7 +306,7 @@ void setPointerUsesSessionAccountIdAsActorPrincipal() { .setAdmissionPointer( org.mockito.ArgumentMatchers.argThat( request -> - request.getActorPrincipal().equals("42") + request.getActorPrincipal().equals(ACCOUNT_UUID) && request.getExpectedPointerVersion() == 3L && request.getExpectedCatalogRevision() == 4L && request.getPreparedVersionUpgradeId().equals("pvu-1"))); @@ -312,7 +314,7 @@ void setPointerUsesSessionAccountIdAsActorPrincipal() { @Test void setPointerMapsVersionMismatchToConflict() { - SessionContext.setContext("42", List.of("platformAdmin"), Map.of()); + SessionContext.setContext(ACCOUNT_UUID, List.of("platformAdmin"), Map.of()); when(gameSessionControlPlaneClient.setAdmissionPointer(any())) .thenReturn( SetAdmissionPointerResponse.newBuilder() @@ -350,8 +352,8 @@ void setPointerMapsVersionMismatchToConflict() { } @Test - void setPointerRejectsMalformedCurrentAccountClaimBeforeMutation() { - SessionContext.setContext("not-a-long", List.of("platformAdmin"), Map.of()); + void setPointerRejectsNonUuidCurrentAccountClaimBeforeMutation() { + SessionContext.setContext("42", List.of("platformAdmin"), Map.of()); ResponseStatusException ex = assertThrows( @@ -382,7 +384,7 @@ void setPointerRejectsMalformedCurrentAccountClaimBeforeMutation() { @Test void executePreparedVersionCutoverUsesSessionAccountIdAsActorPrincipal() { - SessionContext.setContext("42", List.of("platformAdmin"), Map.of()); + SessionContext.setContext(ACCOUNT_UUID, List.of("platformAdmin"), Map.of()); when(gameSessionControlPlaneClient.executePreparedVersionCutover(any())) .thenReturn( ExecutePreparedVersionCutoverResponse.newBuilder() @@ -400,7 +402,7 @@ void executePreparedVersionCutoverUsesSessionAccountIdAsActorPrincipal() { .executePreparedVersionCutover( org.mockito.ArgumentMatchers.argThat( request -> - request.getActorPrincipal().equals("42") + request.getActorPrincipal().equals(ACCOUNT_UUID) && request.getPreparedVersionUpgradeId().equals("pvu-1") && request.getExpectedPointerVersion() == 3L && request.getExpectedCatalogRevision() == 4L)); diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/GameplayCommandStatusServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/GameplayCommandStatusServiceImplTest.java index fb03be9944..5bc2c4411d 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/GameplayCommandStatusServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/GameplayCommandStatusServiceImplTest.java @@ -54,7 +54,7 @@ void getGameplayCommandStatusReturnsCanonicalControlPlaneProjection() { () -> assertEquals(2L, result.tenantId()), () -> assertEquals(7L, result.gameInstanceId()), () -> assertEquals(11L, result.sessionId()), - () -> assertEquals(42L, result.accountId()), + () -> assertEquals("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", result.accountId()), () -> assertEquals(99L, result.characterId()), () -> assertEquals("LOOK", result.commandName()), () -> assertEquals("look", result.sanitizedCommandText()), @@ -255,13 +255,37 @@ void getGameplayCommandStatusRequiresAccessibleTenant() { ResponseStatusException.class, () -> service.getGameplayCommandStatus(2L, 7L, "cmd-123")); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource( + strings = { + "42", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "B8D093F7-CB70-40ED-9FAC-3C82D4BF28F1", + " b8d093f7-cb70-40ed-9fac-3c82d4bf28f1 " + }) + void rejectsMalformedControlPlaneAccountUuid(String account) { + SessionContext.setContext( + "e830a76a-a786-43de-9416-5840fa6e0578", List.of("platformAdmin"), Map.of()); + when(gameSessionControlPlaneClient.getGameplayCommandStatus(2L, 7L, "cmd-123")) + .thenReturn( + GetGameplayCommandStatusResponse.newBuilder() + .setCommand(commandStatus("2").toBuilder().setAccountId(account)) + .build()); + ResponseStatusException failure = + assertThrows( + ResponseStatusException.class, + () -> service.getGameplayCommandStatus(2L, 7L, "cmd-123")); + assertEquals(500, failure.getStatusCode().value()); + } + private GameplayCommandStatus commandStatus(String tenantId) { return GameplayCommandStatus.newBuilder() .setCommandId("cmd-123") .setTenantId(tenantId) .setGameInstanceId("7") .setSessionId("11") - .setAccountId("42") + .setAccountId("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1") .setCharacterId("99") .setCommandName("LOOK") .setSanitizedCommandText("look") diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java index 4efe39ac9f..ef42ead3d8 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java @@ -242,7 +242,7 @@ void applyModerationActionRejectsZeroSessionIdBeforeDispatch() { service.applyModerationAction( ApplyModerationActionRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1") .setSessionId("0") .setAction("ban") .setReason("bad") @@ -282,7 +282,7 @@ void applyModerationActionRejectsAuthorizedCallerWhileMutationGateIsUnavailable( service.applyModerationAction( ApplyModerationActionRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1") .setSessionId("9") .setAction("ban") .setReason("bad") @@ -344,7 +344,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertFalse(ref.get().getAllowed()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertEquals("Malformed claim: accountId", ref.get().getError().getMessage()); verifyNoInteractions(moderationService); } @@ -353,7 +353,8 @@ void evaluateModerationPolicyAllowsAllowlistedInternalService() { SessionContext.setContext( "", List.of(), Map.of(), true, "game-session-service", "test-instance"); ModerationService moderationService = Mockito.mock(ModerationService.class); - when(moderationService.evaluatePolicy(1L, 2L, "CHAT_SEND")) + when(moderationService.evaluatePolicy( + 1L, java.util.UUID.fromString("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"), "CHAT_SEND")) .thenReturn(new ModerationPolicyDecisionDto(true, "", "allowed", null)); LoggingAdminGrpcService service = new LoggingAdminGrpcService( @@ -366,7 +367,7 @@ void evaluateModerationPolicyAllowsAllowlistedInternalService() { service.evaluateModerationPolicy( EvaluateModerationPolicyRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1") .setScope("CHAT_SEND") .build(), new StreamObserver<>() { @@ -385,7 +386,9 @@ public void onCompleted() {} assertNotNull(ref.get()); assertFalse(ref.get().hasError()); assertEquals(true, ref.get().getAllowed()); - verify(moderationService).evaluatePolicy(1L, 2L, "CHAT_SEND"); + verify(moderationService) + .evaluatePolicy( + 1L, java.util.UUID.fromString("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"), "CHAT_SEND"); } @Test @@ -393,7 +396,8 @@ void evaluateModerationPolicyAllowsSocialGroupsInternalService() { SessionContext.setContext( "", List.of(), Map.of(), true, "social-groups-service", "test-instance"); ModerationService moderationService = Mockito.mock(ModerationService.class); - when(moderationService.evaluatePolicy(1L, 2L, "CHAT_SEND")) + when(moderationService.evaluatePolicy( + 1L, java.util.UUID.fromString("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"), "CHAT_SEND")) .thenReturn(new ModerationPolicyDecisionDto(true, "", "allowed", null)); LoggingAdminGrpcService service = new LoggingAdminGrpcService( @@ -406,7 +410,7 @@ void evaluateModerationPolicyAllowsSocialGroupsInternalService() { service.evaluateModerationPolicy( EvaluateModerationPolicyRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1") .setScope("CHAT_SEND") .build(), new StreamObserver<>() { @@ -425,7 +429,9 @@ public void onCompleted() {} assertNotNull(ref.get()); assertFalse(ref.get().hasError()); assertEquals(true, ref.get().getAllowed()); - verify(moderationService).evaluatePolicy(1L, 2L, "CHAT_SEND"); + verify(moderationService) + .evaluatePolicy( + 1L, java.util.UUID.fromString("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"), "CHAT_SEND"); } @Test @@ -443,7 +449,7 @@ void evaluateModerationPolicyRejectsMissingCallerBeforeDispatch() { service.evaluateModerationPolicy( EvaluateModerationPolicyRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1") .setScope("CHAT_SEND") .build(), new StreamObserver<>() { @@ -479,7 +485,7 @@ void evaluateModerationPolicyRejectsAuthenticatedEndUserBeforeDispatch() { service.evaluateModerationPolicy( EvaluateModerationPolicyRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1") .setScope("CHAT_SEND") .build(), new StreamObserver<>() { @@ -515,7 +521,7 @@ void evaluateModerationPolicyRejectsNonAllowlistedInternalServiceBeforeDispatch( service.evaluateModerationPolicy( EvaluateModerationPolicyRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1") .setScope("CHAT_SEND") .build(), new StreamObserver<>() { @@ -551,7 +557,7 @@ void evaluateModerationPolicyRejectsInternalCallerWithMissingServiceNameBeforeDi service.evaluateModerationPolicy( EvaluateModerationPolicyRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1") .setScope("CHAT_SEND") .build(), new StreamObserver<>() { diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java index 23fa8db66f..a4aefa1822 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java @@ -32,13 +32,22 @@ void setup() { @Test void applyActionSavesEntity() throws Exception { - ApplyModerationActionRequest req = new ApplyModerationActionRequest(1L, 2L, 9L, "ban", "test"); + ApplyModerationActionRequest req = + new ApplyModerationActionRequest( + 1L, "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", 9L, "ban", "test"); ModerationAction saved = new ModerationAction(); saved.setId(1L); saved.setCreatedAt(Instant.now()); when(repository.save(any())).thenReturn(saved); ModerationActionDto dto = - new ModerationActionDto(1L, 1L, 2L, "ban", "test", saved.getCreatedAt(), null); + new ModerationActionDto( + 1L, + 1L, + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", + "ban", + "test", + saved.getCreatedAt(), + null); when(mapper.toDto(saved)).thenReturn(dto); ModerationActionDto result = service.applyAction(req); @@ -54,12 +63,17 @@ void evaluatePolicyBlocksGameplayAdmissionForActiveBan() { action.setReason("abuse"); when(repository.findActivePolicyActions( org.mockito.Mockito.eq(1L), - org.mockito.Mockito.eq(2L), + org.mockito.Mockito.eq( + java.util.UUID.fromString("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1")), org.mockito.Mockito.anyList(), org.mockito.Mockito.any())) .thenReturn(List.of(action)); - ModerationPolicyDecisionDto decision = service.evaluatePolicy(1L, 2L, "GAMEPLAY_ADMISSION"); + ModerationPolicyDecisionDto decision = + service.evaluatePolicy( + 1L, + java.util.UUID.fromString("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"), + "GAMEPLAY_ADMISSION"); assertEquals(false, decision.allowed()); assertEquals("gameplay_ban", decision.action()); diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcServiceTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcServiceTest.java index 4e3d815e4b..1f20af7626 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcServiceTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcServiceTest.java @@ -32,8 +32,8 @@ void createReportRejectsWhileMutationGateIsUnavailable() { service.createReport( CreateReportRequest.newBuilder() .setTenantId("1") - .setReporterAccountId("2") - .setTargetAccountId("3") + .setReporterAccountId("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1") + .setTargetAccountId("e830a76a-a786-43de-9416-5840fa6e0578") .setType("BUG") .setDescription("bad") .build(), @@ -70,8 +70,8 @@ void createReportDoesNotDelegateToPersistenceWhileMutationGateIsUnavailable() { service.createReport( CreateReportRequest.newBuilder() .setTenantId("1") - .setReporterAccountId("2") - .setTargetAccountId("3") + .setReporterAccountId("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1") + .setTargetAccountId("e830a76a-a786-43de-9416-5840fa6e0578") .setType("BUG") .setDescription("bad") .build(), @@ -126,7 +126,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("reporterAccountId must be positive", ref.get().getError().getMessage()); + assertEquals("Malformed claim: reporterAccountId", ref.get().getError().getMessage()); } @Test @@ -140,7 +140,7 @@ void createReportRejectsZeroTargetAccountIdBeforeDispatch() { service.createReport( CreateReportRequest.newBuilder() .setTenantId("1") - .setReporterAccountId("2") + .setReporterAccountId("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1") .setTargetAccountId("0") .setType("BUG") .setDescription("bad") @@ -162,7 +162,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("targetAccountId must be positive", ref.get().getError().getMessage()); + assertEquals("Malformed claim: targetAccountId", ref.get().getError().getMessage()); } @Test @@ -174,7 +174,7 @@ void createReportRejectsMissingCallerBeforePersistence() { service.createReport( CreateReportRequest.newBuilder() .setTenantId("1") - .setReporterAccountId("2") + .setReporterAccountId("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1") .setType("BUG") .setDescription("bad") .build(), @@ -206,7 +206,7 @@ void createReportRejectsAuthenticatedEndUserBeforePersistence() { service.createReport( CreateReportRequest.newBuilder() .setTenantId("1") - .setReporterAccountId("2") + .setReporterAccountId("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1") .setType("BUG") .setDescription("bad") .build(), @@ -239,7 +239,7 @@ void createReportRejectsWrongInternalServiceBeforePersistence() { service.createReport( CreateReportRequest.newBuilder() .setTenantId("1") - .setReporterAccountId("2") + .setReporterAccountId("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1") .setType("BUG") .setDescription("bad") .build(), diff --git a/services/social-groups-service/build.gradle.kts b/services/social-groups-service/build.gradle.kts index 2ceeab7615..639f49afa8 100644 --- a/services/social-groups-service/build.gradle.kts +++ b/services/social-groups-service/build.gradle.kts @@ -2,6 +2,7 @@ apply(from = "${rootDir}/gradle/proto-convention.gradle") plugins { + `java-test-fixtures` id("net.firedevops.firemud.secured-stateful-service-conventions") id("net.firedevops.firemud.jooq-conventions") } 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..000b16f6cf 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) { + public Map getPresenceVisibilityPolicies( + long tenantId, Collection accountIds) { if (stub() == null || accountIds == null || accountIds.isEmpty()) { return Map.of(); } - List requestedAccountIds = + List requestedAccountIds = accountIds.stream() - .filter(accountId -> accountId != null && accountId > 0) + .map(accountId -> JwtClaims.requireCanonicalAccountUuid(accountId, "accountId")) .distinct() .toList(); if (requestedAccountIds.isEmpty()) { 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))); + batch.forEach(accountId -> request.addAccountIds(accountId)); ListPresenceVisibilityPoliciesResponse response = callStub().listPresenceVisibilityPolicies(request.build()); @@ -100,21 +103,18 @@ public Map getPresenceVisibilityPolic logger, PRESENCE_VISIBILITY_POLICY_READ_OPERATION, response.getError()); return Map.of(); } - response - .getPoliciesList() - .forEach( - entry -> { - try { - long accountId = Long.parseLong(entry.getAccountId()); - if (accountId > 0 && batch.contains(accountId)) { - policies.put( - accountId, - FriendPresenceVisibilityPolicyValue.valueOf(entry.getPolicy())); - } - } catch (IllegalArgumentException ignored) { - // Missing or malformed policy entries remain fail-closed at the caller. - } - }); + java.util.Set seen = new java.util.HashSet<>(); + for (var entry : response.getPoliciesList()) { + String subject = JwtClaims.requireCanonicalAccountUuid(entry.getAccountId(), "accountId"); + if (!batch.contains(subject) || !seen.add(subject)) { + return Map.of(); + } + try { + policies.put(subject, FriendPresenceVisibilityPolicyValue.valueOf(entry.getPolicy())); + } catch (IllegalArgumentException ignored) { + // Unknown or malformed policy is subject-local private-by-failure. + } + } } return Map.copyOf(policies); } catch (Exception ex) { @@ -128,7 +128,7 @@ public Map getPresenceVisibilityPolic } public boolean updatePresenceVisibilityPolicy( - long tenantId, long accountId, FriendPresenceVisibilityPolicyValue visibilityPolicy) { + long tenantId, String accountId, FriendPresenceVisibilityPolicyValue visibilityPolicy) { if (stub() == null || visibilityPolicy == null) { return false; } @@ -142,7 +142,7 @@ 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()) @@ -176,23 +176,35 @@ 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) { if (stub() == null) { return Optional.empty(); } + JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); 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 profileNode = JsonMapper.builder().build().readTree(response.getProfileJson()); + if (!profileNode.isObject() + || !profileNode.path("accountId").isTextual() + || !accountId.equals( + JwtClaims.requireCanonicalAccountUuid( + profileNode.path("accountId").asString(), "accountId")) + || !profileNode.path("tenantId").isIntegralNumber() + || !profileNode.path("tenantId").canConvertToLong() + || profileNode.path("tenantId").asLong() != tenantId) { + return Optional.empty(); + } AccountProfileJson profile = AccountProfileJson.parse( - response.getProfileJson(), FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY.name()); + response.getProfileJson(), FriendPresenceVisibilityPolicyValue.PRIVATE.name()); FriendPresenceVisibilityPolicyValue resolvedPolicy = FriendPresenceVisibilityPolicyValue.valueOf(profile.presenceVisibilityPolicy()); return Optional.of( 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..3c891f91f8 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) { 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( + JwtClaims.requireCanonicalAccountUuid(viewerAccountId, "viewerAccountId")); + for (String accountId : accountIds) { + request.addAccountIds(JwtClaims.requireCanonicalAccountUuid(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..708d67ec0e 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 @@ -64,12 +64,12 @@ 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) { 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..c358999e2b 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 @@ -61,11 +61,11 @@ protected LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub buildStub( runtimeIdentityProvider.getIfAvailable()); } - public EvaluateModerationPolicyResponse evaluateChatSend(long tenantId, long accountId) { + public EvaluateModerationPolicyResponse evaluateChatSend(long tenantId, String 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..9e97006e25 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.requireCanonicalAccountUuid(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.requireCanonicalAccountUuid(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 941a3f7caf..f9b949de0d 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 @@ -29,7 +29,7 @@ public MailController(MailService mailService, SocialAccessGuard socialAccessGua @PostMapping public ResponseEntity> sendMail( @Valid @RequestBody SendMailRequest request) { - if (!SessionContext.isCurrentAccount(request.senderAccountId())) { + if (!request.senderAccountId().equals(SessionContext.currentAccountUuidOrNull())) { throw new ResponseStatusException( HttpStatus.FORBIDDEN, "Sender must match authenticated account"); } 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..1936ba2f64 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 @@ -2,8 +2,12 @@ import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; +import net.firedevops.firemud.common.security.JwtClaims; public record AddFriendRequest( - @NotNull @Positive Long tenantId, - @NotNull @Positive Long accountId, - @NotNull @Positive Long friendAccountId) {} + @NotNull @Positive Long tenantId, @NotNull String accountId, @NotNull String friendAccountId) { + public AddFriendRequest { + accountId = JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); + friendAccountId = JwtClaims.requireCanonicalAccountUuid(friendAccountId, "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..5ac691c3ab 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 @@ -3,9 +3,14 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; +import net.firedevops.firemud.common.security.JwtClaims; public record AddGuildMemberRequest( @NotNull @Positive Long tenantId, @NotNull @Positive Long guildId, - @NotNull @Positive Long accountId, - @NotBlank String role) {} + @NotNull String accountId, + @NotBlank String role) { + public AddGuildMemberRequest { + accountId = JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); + } +} 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..d1d8fd8e4a 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 @@ -3,9 +3,12 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; +import net.firedevops.firemud.common.security.JwtClaims; /** Request body for creating a guild. */ public record CreateGuildRequest( - @NotNull @Positive Long tenantId, - @NotNull @Positive Long ownerAccountId, - @NotBlank String name) {} + @NotNull @Positive Long tenantId, @NotNull String ownerAccountId, @NotBlank String name) { + public CreateGuildRequest { + ownerAccountId = JwtClaims.requireCanonicalAccountUuid(ownerAccountId, "ownerAccountId"); + } +} 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..d27952aec4 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, + @NotNull 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..3c66e4f68c 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 @@ -3,10 +3,17 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; +import net.firedevops.firemud.common.security.JwtClaims; public record SendMailRequest( @NotNull @Positive Long tenantId, - @NotNull @Positive Long senderAccountId, - @NotNull @Positive Long recipientAccountId, + @NotNull String senderAccountId, + @NotNull String recipientAccountId, @NotBlank String subject, - @NotBlank String content) {} + @NotBlank String content) { + public SendMailRequest { + senderAccountId = JwtClaims.requireCanonicalAccountUuid(senderAccountId, "senderAccountId"); + recipientAccountId = + JwtClaims.requireCanonicalAccountUuid(recipientAccountId, "recipientAccountId"); + } +} 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..1bc18ea6a1 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 @@ -3,15 +3,24 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; +import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.socialgroups.enums.ChatType; public record SendMessageRequestDto( @NotNull @Positive Long tenantId, - @NotNull @Positive Long senderAccountId, + @NotNull String senderAccountId, ChatType type, String channelId, - @Positive Long recipientAccountId, + String recipientAccountId, @Positive Long guildId, @Positive Long cityId, @NotBlank String content, - String effectId) {} + String effectId) { + public SendMessageRequestDto { + senderAccountId = JwtClaims.requireCanonicalAccountUuid(senderAccountId, "senderAccountId"); + recipientAccountId = + recipientAccountId == null + ? null + : JwtClaims.requireCanonicalAccountUuid(recipientAccountId, "recipientAccountId"); + } +} 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..11fa738df2 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 @@ -2,8 +2,13 @@ import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; +import net.firedevops.firemud.common.security.JwtClaims; public record UpdateFriendPresencePolicyRequest( @Positive long tenantId, - @Positive long accountId, - @NotNull FriendPresenceVisibilityPolicyValue visibilityPolicy) {} + String accountId, + @NotNull FriendPresenceVisibilityPolicyValue visibilityPolicy) { + public UpdateFriendPresencePolicyRequest { + accountId = JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); + } +} 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..99db5878b3 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 @@ -3,9 +3,14 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; +import net.firedevops.firemud.common.security.JwtClaims; public record UpdateGuildMemberRoleRequest( @NotNull @Positive Long tenantId, @NotNull @Positive Long guildId, - @NotNull @Positive Long accountId, - @NotBlank String role) {} + @NotNull String accountId, + @NotBlank String role) { + public UpdateGuildMemberRoleRequest { + accountId = JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); + } +} 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..5324d1622a 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 @@ -3,9 +3,12 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; +import net.firedevops.firemud.common.security.JwtClaims; /** 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, @NotNull String accountId, @NotBlank String channelId) { + public VoiceTokenRequestDto { + accountId = JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); + } +} 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..cda725bb73 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 @@ -8,8 +8,8 @@ public class AccountFriendLink { private Long id; private Long tenantId; - private Long accountId; - private Long friendAccountId; + private String accountId; + private String 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..a151fd94fc 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 @@ -8,7 +8,7 @@ public class ChatMessage { private Long id; private Long tenantId; - private Long senderAccountId; + private String senderAccountId; private String content; private Instant timestamp; @@ -16,7 +16,7 @@ public class ChatMessage { private Long cityId; - private Long recipientAccountId; + private String 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..eddd19a94a 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 @@ -8,6 +8,6 @@ public class Guild { private Long id; private Long tenantId; private String name; - private Long ownerAccountId; + private String 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..15b5ee7df4 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 @@ -7,6 +7,6 @@ public class GuildMember { private Long id; private Long tenantId; private Long guildId; - private Long accountId; + private String 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..ed4f40d8c6 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 @@ -7,8 +7,8 @@ public class MailMessage { private Long id; private Long tenantId; - private Long senderAccountId; - private Long recipientAccountId; + private String senderAccountId; + private String 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..09a14dac32 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 @@ -24,14 +24,16 @@ public AccountFriendLinkRepository(DSLContext dsl) { } public List findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( - Long tenantId, Long accountId, String status) { + Long tenantId, String accountId, String status) { var reciprocal = ACCOUNT_FRIEND_LINKS.as("reciprocal_friend_link"); return dsl.selectFrom(ACCOUNT_FRIEND_LINKS) .where( ACCOUNT_FRIEND_LINKS .TENANT_ID .eq(tenantId) - .and(ACCOUNT_FRIEND_LINKS.ACCOUNT_ID.eq(accountId)) + .and( + ACCOUNT_FRIEND_LINKS.ACCOUNT_ID.eq( + JooqSocialGroupsRepositorySupport.toAccountUuid(accountId))) .and(ACCOUNT_FRIEND_LINKS.STATUS.eq(status)) .andExists( dsl.selectOne() @@ -52,27 +54,33 @@ public List findMutuallyAcceptedByTenantIdAndAccountIdAndStat } public List findByTenantIdAndAccountIdAndStatus( - Long tenantId, Long accountId, String status) { + Long tenantId, String accountId, String status) { return dsl.selectFrom(ACCOUNT_FRIEND_LINKS) .where( ACCOUNT_FRIEND_LINKS .TENANT_ID .eq(tenantId) - .and(ACCOUNT_FRIEND_LINKS.ACCOUNT_ID.eq(accountId)) + .and( + ACCOUNT_FRIEND_LINKS.ACCOUNT_ID.eq( + JooqSocialGroupsRepositorySupport.toAccountUuid(accountId))) .and(ACCOUNT_FRIEND_LINKS.STATUS.eq(status))) .orderBy(ACCOUNT_FRIEND_LINKS.ID.asc()) .fetch(this::toEntity); } public Optional findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( - Long tenantId, Long accountId, Long friendAccountId, String status) { + Long tenantId, String accountId, String friendAccountId, String status) { return dsl.selectFrom(ACCOUNT_FRIEND_LINKS) .where( ACCOUNT_FRIEND_LINKS .TENANT_ID .eq(tenantId) - .and(ACCOUNT_FRIEND_LINKS.ACCOUNT_ID.eq(accountId)) - .and(ACCOUNT_FRIEND_LINKS.FRIEND_ACCOUNT_ID.eq(friendAccountId)) + .and( + ACCOUNT_FRIEND_LINKS.ACCOUNT_ID.eq( + JooqSocialGroupsRepositorySupport.toAccountUuid(accountId))) + .and( + ACCOUNT_FRIEND_LINKS.FRIEND_ACCOUNT_ID.eq( + JooqSocialGroupsRepositorySupport.toAccountUuid(friendAccountId))) .and(ACCOUNT_FRIEND_LINKS.STATUS.eq(status))) .orderBy(ACCOUNT_FRIEND_LINKS.ID.asc()) .limit(1) @@ -90,8 +98,12 @@ public AccountFriendLink save(AccountFriendLink entity) { int updated = dsl.update(ACCOUNT_FRIEND_LINKS) .set(ACCOUNT_FRIEND_LINKS.TENANT_ID, entity.getTenantId()) - .set(ACCOUNT_FRIEND_LINKS.ACCOUNT_ID, entity.getAccountId()) - .set(ACCOUNT_FRIEND_LINKS.FRIEND_ACCOUNT_ID, entity.getFriendAccountId()) + .set( + ACCOUNT_FRIEND_LINKS.ACCOUNT_ID, + JooqSocialGroupsRepositorySupport.toAccountUuid(entity.getAccountId())) + .set( + ACCOUNT_FRIEND_LINKS.FRIEND_ACCOUNT_ID, + JooqSocialGroupsRepositorySupport.toAccountUuid(entity.getFriendAccountId())) .set(ACCOUNT_FRIEND_LINKS.STATUS, entity.getStatus()) .set( ACCOUNT_FRIEND_LINKS.CREATED_AT, @@ -126,8 +138,9 @@ private Optional findById(Long id) { private void populate(AccountFriendLinksRecord record, AccountFriendLink entity) { record.setTenantId(entity.getTenantId()); - record.setAccountId(entity.getAccountId()); - record.setFriendAccountId(entity.getFriendAccountId()); + record.setAccountId(JooqSocialGroupsRepositorySupport.toAccountUuid(entity.getAccountId())); + record.setFriendAccountId( + JooqSocialGroupsRepositorySupport.toAccountUuid(entity.getFriendAccountId())); record.setStatus(entity.getStatus()); record.setCreatedAt(JooqSocialGroupsRepositorySupport.toLocalDateTime(entity.getCreatedAt())); } @@ -136,8 +149,12 @@ private AccountFriendLink toEntity(Record record) { AccountFriendLink entity = new AccountFriendLink(); entity.setId(record.get(ACCOUNT_FRIEND_LINKS.ID)); entity.setTenantId(record.get(ACCOUNT_FRIEND_LINKS.TENANT_ID)); - entity.setAccountId(record.get(ACCOUNT_FRIEND_LINKS.ACCOUNT_ID)); - entity.setFriendAccountId(record.get(ACCOUNT_FRIEND_LINKS.FRIEND_ACCOUNT_ID)); + entity.setAccountId( + JooqSocialGroupsRepositorySupport.fromAccountUuid( + record.get(ACCOUNT_FRIEND_LINKS.ACCOUNT_ID))); + entity.setFriendAccountId( + JooqSocialGroupsRepositorySupport.fromAccountUuid( + record.get(ACCOUNT_FRIEND_LINKS.FRIEND_ACCOUNT_ID))); entity.setStatus(record.get(ACCOUNT_FRIEND_LINKS.STATUS)); entity.setCreatedAt( JooqSocialGroupsRepositorySupport.toInstant(record.get(ACCOUNT_FRIEND_LINKS.CREATED_AT))); diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/ChatMessageRepository.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/ChatMessageRepository.java index 3942f8300c..bb02c502c9 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/ChatMessageRepository.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/ChatMessageRepository.java @@ -40,14 +40,19 @@ public ChatMessage save(ChatMessage entity) { int updated = dsl.update(CHAT_MESSAGES) .set(CHAT_MESSAGES.TENANT_ID, entity.getTenantId()) - .set(CHAT_MESSAGES.SENDER_ACCOUNT_ID, entity.getSenderAccountId()) + .set( + CHAT_MESSAGES.SENDER_ACCOUNT_ID, + JooqSocialGroupsRepositorySupport.toAccountUuid(entity.getSenderAccountId())) .set(CHAT_MESSAGES.CONTENT, entity.getContent()) .set( CHAT_MESSAGES.TIMESTAMP, JooqSocialGroupsRepositorySupport.toLocalDateTime(entity.getTimestamp())) .set(CHAT_MESSAGES.GUILD_ID, entity.getGuildId()) .set(CHAT_MESSAGES.CITY_ID, entity.getCityId()) - .set(CHAT_MESSAGES.RECIPIENT_ACCOUNT_ID, entity.getRecipientAccountId()) + .set( + CHAT_MESSAGES.RECIPIENT_ACCOUNT_ID, + JooqSocialGroupsRepositorySupport.toOptionalAccountUuid( + entity.getRecipientAccountId())) .set(CHAT_MESSAGES.EFFECT_ID, entity.getEffectId()) .set(CHAT_MESSAGES.TYPE, entity.getType() == null ? null : entity.getType().name()) .where(CHAT_MESSAGES.ID.eq(entity.getId())) @@ -66,12 +71,14 @@ private Optional findById(Long id) { private void populate(ChatMessagesRecord record, ChatMessage entity) { record.setTenantId(entity.getTenantId()); - record.setSenderAccountId(entity.getSenderAccountId()); + record.setSenderAccountId( + JooqSocialGroupsRepositorySupport.toAccountUuid(entity.getSenderAccountId())); record.setContent(entity.getContent()); record.setTimestamp(JooqSocialGroupsRepositorySupport.toLocalDateTime(entity.getTimestamp())); record.setGuildId(entity.getGuildId()); record.setCityId(entity.getCityId()); - record.setRecipientAccountId(entity.getRecipientAccountId()); + record.setRecipientAccountId( + JooqSocialGroupsRepositorySupport.toOptionalAccountUuid(entity.getRecipientAccountId())); record.setEffectId(entity.getEffectId()); record.setType(entity.getType() == null ? null : entity.getType().name()); } @@ -80,13 +87,17 @@ private ChatMessage toEntity(Record record) { ChatMessage entity = new ChatMessage(); entity.setId(record.get(CHAT_MESSAGES.ID)); entity.setTenantId(record.get(CHAT_MESSAGES.TENANT_ID)); - entity.setSenderAccountId(record.get(CHAT_MESSAGES.SENDER_ACCOUNT_ID)); + entity.setSenderAccountId( + JooqSocialGroupsRepositorySupport.fromAccountUuid( + record.get(CHAT_MESSAGES.SENDER_ACCOUNT_ID))); entity.setContent(record.get(CHAT_MESSAGES.CONTENT)); entity.setTimestamp( JooqSocialGroupsRepositorySupport.toInstant(record.get(CHAT_MESSAGES.TIMESTAMP))); entity.setGuildId(record.get(CHAT_MESSAGES.GUILD_ID)); entity.setCityId(record.get(CHAT_MESSAGES.CITY_ID)); - entity.setRecipientAccountId(record.get(CHAT_MESSAGES.RECIPIENT_ACCOUNT_ID)); + entity.setRecipientAccountId( + JooqSocialGroupsRepositorySupport.fromAccountUuid( + record.get(CHAT_MESSAGES.RECIPIENT_ACCOUNT_ID))); entity.setEffectId(record.get(CHAT_MESSAGES.EFFECT_ID)); String type = record.get(CHAT_MESSAGES.TYPE); entity.setType(type == null ? null : ChatType.valueOf(type)); 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..89e945e5c5 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 @@ -22,14 +22,16 @@ public GuildMemberRepository(DSLContext dsl) { } public Optional findFirstByTenantIdAndGuildIdAndAccountId( - Long tenantId, Long guildId, Long accountId) { + Long tenantId, Long guildId, String accountId) { return dsl.selectFrom(GUILD_MEMBERS) .where( GUILD_MEMBERS .TENANT_ID .eq(tenantId) .and(GUILD_MEMBERS.GUILD_ID.eq(guildId)) - .and(GUILD_MEMBERS.ACCOUNT_ID.eq(accountId))) + .and( + GUILD_MEMBERS.ACCOUNT_ID.eq( + JooqSocialGroupsRepositorySupport.toAccountUuid(accountId)))) .limit(1) .fetchOptional(this::toEntity); } @@ -46,7 +48,9 @@ public GuildMember save(GuildMember entity) { dsl.update(GUILD_MEMBERS) .set(GUILD_MEMBERS.TENANT_ID, entity.getTenantId()) .set(GUILD_MEMBERS.GUILD_ID, entity.getGuildId()) - .set(GUILD_MEMBERS.ACCOUNT_ID, entity.getAccountId()) + .set( + GUILD_MEMBERS.ACCOUNT_ID, + JooqSocialGroupsRepositorySupport.toAccountUuid(entity.getAccountId())) .set(GUILD_MEMBERS.ROLE, entity.getRole()) .where(GUILD_MEMBERS.ID.eq(entity.getId())) .execute(); @@ -72,7 +76,7 @@ private Optional findById(Long id) { private void populate(GuildMembersRecord record, GuildMember entity) { record.setTenantId(entity.getTenantId()); record.setGuildId(entity.getGuildId()); - record.setAccountId(entity.getAccountId()); + record.setAccountId(JooqSocialGroupsRepositorySupport.toAccountUuid(entity.getAccountId())); record.setRole(entity.getRole()); } @@ -81,7 +85,8 @@ private GuildMember toEntity(Record record) { entity.setId(record.get(GUILD_MEMBERS.ID)); entity.setTenantId(record.get(GUILD_MEMBERS.TENANT_ID)); entity.setGuildId(record.get(GUILD_MEMBERS.GUILD_ID)); - entity.setAccountId(record.get(GUILD_MEMBERS.ACCOUNT_ID)); + entity.setAccountId( + JooqSocialGroupsRepositorySupport.fromAccountUuid(record.get(GUILD_MEMBERS.ACCOUNT_ID))); entity.setRole(record.get(GUILD_MEMBERS.ROLE)); return entity; } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/GuildRepository.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/GuildRepository.java index ab5b8677e1..27304687e0 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/GuildRepository.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/GuildRepository.java @@ -33,7 +33,9 @@ public Guild save(Guild entity) { dsl.update(GUILDS) .set(GUILDS.TENANT_ID, entity.getTenantId()) .set(GUILDS.NAME, entity.getName()) - .set(GUILDS.OWNER_ACCOUNT_ID, entity.getOwnerAccountId()) + .set( + GUILDS.OWNER_ACCOUNT_ID, + JooqSocialGroupsRepositorySupport.toAccountUuid(entity.getOwnerAccountId())) .set( GUILDS.CREATED_AT, JooqSocialGroupsRepositorySupport.toLocalDateTime(entity.getCreatedAt())) @@ -52,7 +54,8 @@ private Optional findById(Long id) { private void populate(GuildsRecord record, Guild entity) { record.setTenantId(entity.getTenantId()); record.setName(entity.getName()); - record.setOwnerAccountId(entity.getOwnerAccountId()); + record.setOwnerAccountId( + JooqSocialGroupsRepositorySupport.toAccountUuid(entity.getOwnerAccountId())); record.setCreatedAt(JooqSocialGroupsRepositorySupport.toLocalDateTime(entity.getCreatedAt())); } @@ -61,7 +64,8 @@ private Guild toEntity(Record record) { entity.setId(record.get(GUILDS.ID)); entity.setTenantId(record.get(GUILDS.TENANT_ID)); entity.setName(record.get(GUILDS.NAME)); - entity.setOwnerAccountId(record.get(GUILDS.OWNER_ACCOUNT_ID)); + entity.setOwnerAccountId( + JooqSocialGroupsRepositorySupport.fromAccountUuid(record.get(GUILDS.OWNER_ACCOUNT_ID))); entity.setCreatedAt(JooqSocialGroupsRepositorySupport.toInstant(record.get(GUILDS.CREATED_AT))); return entity; } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/JooqSocialGroupsRepositorySupport.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/JooqSocialGroupsRepositorySupport.java index 9b9398e85b..a327725982 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/JooqSocialGroupsRepositorySupport.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/JooqSocialGroupsRepositorySupport.java @@ -2,11 +2,27 @@ import java.time.Instant; import java.time.LocalDateTime; +import java.util.UUID; import net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport; +import net.firedevops.firemud.common.security.JwtClaims; final class JooqSocialGroupsRepositorySupport { private JooqSocialGroupsRepositorySupport() {} + static UUID toAccountUuid(String value) { + return UUID.fromString(JwtClaims.requireCanonicalAccountUuid(value, "accountId")); + } + + static UUID toOptionalAccountUuid(String value) { + return value == null ? null : toAccountUuid(value); + } + + static String fromAccountUuid(UUID value) { + return value == null + ? null + : JwtClaims.requireCanonicalAccountUuid(value.toString(), "accountId"); + } + static LocalDateTime toLocalDateTime(Instant instant) { return JooqPersistenceSupport.toLocalDateTime(instant); } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/MailMessageRepository.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/MailMessageRepository.java index e0d9061d3b..16013d24bd 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/MailMessageRepository.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/repository/MailMessageRepository.java @@ -32,8 +32,12 @@ public MailMessage save(MailMessage entity) { int updated = dsl.update(MAIL_MESSAGES) .set(MAIL_MESSAGES.TENANT_ID, entity.getTenantId()) - .set(MAIL_MESSAGES.SENDER_ACCOUNT_ID, entity.getSenderAccountId()) - .set(MAIL_MESSAGES.RECIPIENT_ACCOUNT_ID, entity.getRecipientAccountId()) + .set( + MAIL_MESSAGES.SENDER_ACCOUNT_ID, + JooqSocialGroupsRepositorySupport.toAccountUuid(entity.getSenderAccountId())) + .set( + MAIL_MESSAGES.RECIPIENT_ACCOUNT_ID, + JooqSocialGroupsRepositorySupport.toAccountUuid(entity.getRecipientAccountId())) .set(MAIL_MESSAGES.SUBJECT, entity.getSubject()) .set(MAIL_MESSAGES.CONTENT, entity.getContent()) .set( @@ -58,8 +62,10 @@ private Optional findById(Long id) { private void populate(MailMessagesRecord record, MailMessage entity) { record.setTenantId(entity.getTenantId()); - record.setSenderAccountId(entity.getSenderAccountId()); - record.setRecipientAccountId(entity.getRecipientAccountId()); + record.setSenderAccountId( + JooqSocialGroupsRepositorySupport.toAccountUuid(entity.getSenderAccountId())); + record.setRecipientAccountId( + JooqSocialGroupsRepositorySupport.toAccountUuid(entity.getRecipientAccountId())); record.setSubject(entity.getSubject()); record.setContent(entity.getContent()); record.setSentAt(JooqSocialGroupsRepositorySupport.toLocalDateTime(entity.getSentAt())); @@ -70,8 +76,12 @@ private MailMessage toEntity(Record record) { MailMessage entity = new MailMessage(); entity.setId(record.get(MAIL_MESSAGES.ID)); entity.setTenantId(record.get(MAIL_MESSAGES.TENANT_ID)); - entity.setSenderAccountId(record.get(MAIL_MESSAGES.SENDER_ACCOUNT_ID)); - entity.setRecipientAccountId(record.get(MAIL_MESSAGES.RECIPIENT_ACCOUNT_ID)); + entity.setSenderAccountId( + JooqSocialGroupsRepositorySupport.fromAccountUuid( + record.get(MAIL_MESSAGES.SENDER_ACCOUNT_ID))); + entity.setRecipientAccountId( + JooqSocialGroupsRepositorySupport.fromAccountUuid( + record.get(MAIL_MESSAGES.RECIPIENT_ACCOUNT_ID))); entity.setSubject(record.get(MAIL_MESSAGES.SUBJECT)); entity.setContent(record.get(MAIL_MESSAGES.CONTENT)); entity.setSentAt( 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 3054782bf5..806894b71b 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,5 +1,6 @@ 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; @@ -7,21 +8,29 @@ @Component public class SocialAccessGuard { - public void requireAccountAccess(long tenantId, long accountId) { + public void requireAccountAccess(long tenantId, String accountId) { if (!hasAccountAccess(tenantId, accountId)) { throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Account access required"); } } - public boolean hasAccountAccess(long tenantId, long accountId) { - return SessionContext.hasTenantAccess(tenantId) || isCurrentAccount(accountId); + public boolean hasAccountAccess(long tenantId, String accountId) { + if (tenantId <= 0) { + return false; + } + return isCurrentAccount(accountId); } public void requireTenantAccess(long tenantId) { SessionContext.requireTenantAccess(tenantId); } - private boolean isCurrentAccount(long accountId) { - return SessionContext.isCurrentAccount(accountId); + private boolean isCurrentAccount(String accountId) { + try { + return JwtClaims.requireCanonicalAccountUuid(accountId, "accountId") + .equals(SessionContext.currentAccountUuidOrNull()); + } catch (IllegalArgumentException ex) { + return false; + } } } 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..fa2b75e09d 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 @@ -142,7 +142,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 +158,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 +186,8 @@ 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, accountId); try { java.util.List raw = redisTemplate.opsForList().range(key, 0, -1); return raw == null @@ -201,13 +201,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 +215,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) { 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..106756df1e 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 @@ -8,6 +8,7 @@ import java.util.Optional; 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; @@ -68,7 +69,7 @@ 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) { validateNotSelfLink(accountId, friendAccountId); accountFriendLinkRepository .findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( @@ -79,19 +80,18 @@ public void removeFriend(long tenantId, long accountId, long friendAccountId) { @Override @Timed(value = "friend.get") public Optional getFriend( - long tenantId, long accountId, long friendAccountId) { + long tenantId, String accountId, String friendAccountId) { return listFriends(tenantId, accountId, FriendRosterFilter.ALL).friends().stream() .filter( entry -> - entry.friendAccountId() != null - && entry.friendAccountId().longValue() == friendAccountId) + entry.friendAccountId() != null && entry.friendAccountId().equals(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 +102,16 @@ 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) { + JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); + JwtClaims.requireCanonicalAccountUuid(friendAccountId, "friendAccountId"); + if (accountId.equals(friendAccountId)) { throw new IllegalArgumentException("Cannot add or remove your own account as a friend"); } } @@ -142,12 +144,13 @@ private FriendLinkDto toDto(AccountFriendLink link) { @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) { FriendRosterFilter effectiveFilter = normalizeRosterFilter(filter); List links = accountFriendLinkRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( @@ -157,18 +160,18 @@ private FriendRosterSnapshot loadFriendRoster( new FriendRosterViewDto(effectiveFilter, 0, 0, List.of()), Map.of()); } - List friendAccountIds = + List friendAccountIds = links.stream().map(AccountFriendLink::getFriendAccountId).distinct().toList(); - Map visibilityPolicies = + 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 +189,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 +238,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 +249,7 @@ public FriendPresenceViewDto listFriendPresence( @Override @Timed(value = "friend.visibility.get") - public FriendPresencePolicyViewDto getFriendPresencePolicy(long tenantId, long accountId) { + public FriendPresencePolicyViewDto getFriendPresencePolicy(long tenantId, String accountId) { FriendPresenceVisibilityPolicyValue visibilityPolicy = accountClient .getPresenceVisibilityPolicy(tenantId, accountId) @@ -258,7 +261,7 @@ 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) { validateVisibilityPolicy(visibilityPolicy); if (!accountClient.updatePresenceVisibilityPolicy(tenantId, accountId, visibilityPolicy)) { throw new IllegalStateException("Friend presence visibility update unavailable"); @@ -267,7 +270,7 @@ public FriendPresencePolicyViewDto updateFriendPresencePolicy( } private FriendRosterEntryDto toRosterEntry( - int ordinal, AccountFriendLink link, Map byAccountId) { + int ordinal, AccountFriendLink link, Map byAccountId) { return new FriendRosterEntryDto( ordinal, link.getId(), @@ -283,7 +286,7 @@ private FriendRosterEntryDto toRosterEntry( private boolean matchesFilter( FriendRosterFilter filter, FriendRosterEntryDto entry, - Map visibilityPolicies) { + Map visibilityPolicies) { FriendPresenceDto presence = entry.presence(); return switch (filter) { case ALL -> true; @@ -311,11 +314,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 +331,12 @@ 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 = requirePresenceAccountUuid(entry.getAccountId()); + if (!friendAccountIds.contains(friendAccountId) || byAccountId.containsKey(friendAccountId)) { + throw new IllegalStateException("Unrequested account presence subject"); + } byAccountId.put( friendAccountId, mapPresence( @@ -347,7 +353,7 @@ private boolean canQueryPresence(FriendPresenceVisibilityPolicyValue visibilityP } private FriendPresenceDto mapPresence( - long friendAccountId, + String friendAccountId, AccountPresenceEntry entry, FriendPresenceVisibilityPolicyValue visibilityPolicy) { if (visibilityPolicy != FriendPresenceVisibilityPolicyValue.PUBLIC @@ -372,7 +378,7 @@ private FriendPresenceDto mapPresence( null); } - private FriendPresenceDto defaultPresence(long friendAccountId) { + private FriendPresenceDto defaultPresence(String friendAccountId) { return new FriendPresenceDto( friendAccountId, false, @@ -502,7 +508,7 @@ private Instant visibleLastSeenAt( } private FriendPresenceVisibilityPolicyValue visibilityPolicyFor( - long accountId, Map visibilityPolicies) { + String accountId, Map visibilityPolicies) { if (visibilityPolicies == null) { return FriendPresenceVisibilityPolicyValue.PRIVATE; } @@ -521,24 +527,24 @@ private FriendPresenceVisibilityPolicyValue normalizeVisibilityPolicy( }; } - private Long parseOptionalPositivePresenceId(String value, String fieldName) { + private String requirePresenceAccountUuid(String value) { try { - return RequestIdValidation.parseOptionalPositiveLong(value, fieldName); + return JwtClaims.requireCanonicalAccountUuid(value, "accountId"); } catch (IllegalArgumentException ex) { - return null; + throw new IllegalStateException( + "Malformed account presence accountId: " + ex.getMessage(), ex); } } - private long requirePositivePresenceId(String value, String fieldName) { + private Long parseOptionalPositivePresenceId(String value, String fieldName) { try { - return RequestIdValidation.requirePositiveLong(value, fieldName); + return RequestIdValidation.parseOptionalPositiveLong(value, fieldName); } catch (IllegalArgumentException ex) { - throw new IllegalStateException( - "Malformed account presence " + fieldName + ": " + ex.getMessage(), ex); + return null; } } 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..4fd4562772 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 @@ -140,7 +140,7 @@ public GuildMemberDto updateMemberRole(UpdateGuildMemberRoleRequest request) { @Override @Transactional @Timed(value = "guild.removeMember") - public void removeMember(long tenantId, long guildId, long accountId) { + public void removeMember(long tenantId, long guildId, String accountId) { logger.info("Removing member {} from guild {}", accountId, guildId); GuildMember member = guildMemberRepository @@ -153,7 +153,7 @@ public void removeMember(long tenantId, long guildId, long accountId) { runAfterCommit(() -> safeReportModeration(tenantId, accountId, "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) { 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..801552b84a 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,6 +7,7 @@ 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.socialgroups.dto.AddFriendRequest; import net.firedevops.firemud.socialgroups.dto.CreateGuildRequest; @@ -104,8 +105,7 @@ public void sendMessage( senderScope.accountId(), mapChatType(request), request.getChannelId(), - RequestIdValidation.parseOptionalPositiveLong( - request.getRecipientId(), "recipientId"), + optionalAccountUuid(request.getRecipientId(), "recipientId"), RequestIdValidation.parseOptionalPositiveLong(request.getGuildId(), "guildId"), RequestIdValidation.parseOptionalPositiveLong(request.getCityId(), "cityId"), request.getContent(), @@ -122,6 +122,13 @@ public void sendMessage( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AuthorizationException ex) { + responseObserver.onNext( + SendMessageResponse.newBuilder() + .setSuccess(false) + .setError(permissionDenied("SendMessage", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (Exception ex) { SendMessageResponse response = SendMessageResponse.newBuilder() @@ -169,6 +176,12 @@ public void createGuild( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AuthorizationException ex) { + responseObserver.onNext( + CreateGuildResponse.newBuilder() + .setError(permissionDenied("CreateGuild", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (Exception ex) { CreateGuildResponse response = CreateGuildResponse.newBuilder().setError(internal("CreateGuild", ex)).build(); @@ -189,7 +202,7 @@ public void addFriend( new AddFriendRequest( accountScope.tenantId(), accountScope.accountId(), - RequestIdValidation.requirePositiveLong( + JwtClaims.requireCanonicalAccountUuid( request.getFriendAccountId(), "friendAccountId")); friendService.addFriend(dto); AddFriendResponse response = AddFriendResponse.newBuilder().setSuccess(true).build(); @@ -203,6 +216,13 @@ public void addFriend( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AuthorizationException ex) { + responseObserver.onNext( + AddFriendResponse.newBuilder() + .setSuccess(false) + .setError(permissionDenied("AddFriend", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (Exception ex) { AddFriendResponse response = AddFriendResponse.newBuilder() @@ -224,7 +244,7 @@ public void removeFriend( friendService.removeFriend( accountScope.tenantId(), accountScope.accountId(), - RequestIdValidation.requirePositiveLong(request.getFriendAccountId(), "friendAccountId")); + JwtClaims.requireCanonicalAccountUuid(request.getFriendAccountId(), "friendAccountId")); responseObserver.onNext(RemoveFriendResponse.newBuilder().setSuccess(true).build()); responseObserver.onCompleted(); } catch (IllegalArgumentException ex) { @@ -261,8 +281,8 @@ public void getFriend( try { AccountScope accountScope = requireAccountScope(request.getTenantId(), request.getAccountId(), "accountId"); - long friendAccountId = - RequestIdValidation.requirePositiveLong(request.getFriendAccountId(), "friendAccountId"); + String friendAccountId = + JwtClaims.requireCanonicalAccountUuid(request.getFriendAccountId(), "friendAccountId"); FriendRosterEntryDto friend = friendService .getFriend(accountScope.tenantId(), accountScope.accountId(), friendAccountId) @@ -623,7 +643,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 +691,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 +700,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()); @@ -774,7 +794,7 @@ public void sendMail( new SendMailRequest( senderScope.tenantId(), senderScope.accountId(), - RequestIdValidation.requirePositiveLong( + JwtClaims.requireCanonicalAccountUuid( request.getRecipientAccountId(), "recipientAccountId"), request.getSubject(), request.getContent()); @@ -832,7 +852,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 +862,18 @@ 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.requireCanonicalAccountUuid(accountIdText, accountFieldName); requireAccountAccess(tenantId, accountId); return new AccountScope(tenantId, accountId); } - private record AccountScope(long tenantId, long accountId) {} + private String optionalAccountUuid(String value, String fieldName) { + return value == null || value.isEmpty() + ? null + : JwtClaims.requireCanonicalAccountUuid(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/resources/db/migration/V10__canonical_account_uuid_carriers.sql b/services/social-groups-service/src/main/resources/db/migration/V10__canonical_account_uuid_carriers.sql new file mode 100644 index 0000000000..fed33d4a3e --- /dev/null +++ b/services/social-groups-service/src/main/resources/db/migration/V10__canonical_account_uuid_carriers.sql @@ -0,0 +1,72 @@ +-- Account owns the ordinary Account UUID. Social cannot reconstruct it from private BIGINT keys. +-- Populated legacy deployments require a genuine Account-owner mapping and retained-data disposition +-- before deploying this migration. No row is deleted, guessed, or copied into a parallel authority. +-- Flyway runs this migration transactionally: hold write-excluding locks through the emptiness guard +-- and every ALTER so no concurrent legacy write can cross the verified-empty source boundary. +-- [jooq ignore start] +LOCK TABLE guilds, guild_members, chat_messages, friend_links, mail_messages, + account_friend_links IN ACCESS EXCLUSIVE MODE; +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 friend_links) + OR EXISTS (SELECT 1 FROM mail_messages) + OR EXISTS (SELECT 1 FROM account_friend_links) THEN + RAISE EXCEPTION 'SOCIAL_ACCOUNT_UUID_MIGRATION_BLOCKED: retained legacy Account references require genuine Account-owner mapping and disposition; no rows were changed'; + END IF; +END $$; +-- [jooq ignore stop] + +ALTER TABLE guilds ALTER COLUMN owner_account_id TYPE UUID -- [jooq ignore start] +USING owner_account_id::text::uuid -- [jooq ignore stop] +; +ALTER TABLE guild_members ALTER COLUMN account_id TYPE UUID -- [jooq ignore start] +USING account_id::text::uuid -- [jooq ignore stop] +; +ALTER TABLE chat_messages ALTER COLUMN sender_account_id TYPE UUID -- [jooq ignore start] +USING sender_account_id::text::uuid -- [jooq ignore stop] +; +ALTER TABLE chat_messages ALTER COLUMN recipient_account_id TYPE UUID -- [jooq ignore start] +USING recipient_account_id::text::uuid -- [jooq ignore stop] +; +ALTER TABLE friend_links ALTER COLUMN account_id TYPE UUID -- [jooq ignore start] +USING account_id::text::uuid -- [jooq ignore stop] +; +ALTER TABLE friend_links ALTER COLUMN friend_account_id TYPE UUID -- [jooq ignore start] +USING friend_account_id::text::uuid -- [jooq ignore stop] +; +ALTER TABLE mail_messages ALTER COLUMN sender_account_id TYPE UUID -- [jooq ignore start] +USING sender_account_id::text::uuid -- [jooq ignore stop] +; +ALTER TABLE mail_messages ALTER COLUMN recipient_account_id TYPE UUID -- [jooq ignore start] +USING recipient_account_id::text::uuid -- [jooq ignore stop] +; +ALTER TABLE account_friend_links ALTER COLUMN account_id TYPE UUID -- [jooq ignore start] +USING account_id::text::uuid -- [jooq ignore stop] +; +ALTER TABLE account_friend_links ALTER COLUMN friend_account_id TYPE UUID -- [jooq ignore start] +USING friend_account_id::text::uuid -- [jooq ignore stop] +; + +ALTER TABLE guilds ADD CONSTRAINT ck_guild_owner_account_uuid_non_nil + CHECK (owner_account_id <> '00000000-0000-0000-0000-000000000000'::uuid); +ALTER TABLE guild_members ADD CONSTRAINT ck_guild_member_account_uuid_non_nil + CHECK (account_id <> '00000000-0000-0000-0000-000000000000'::uuid); +ALTER TABLE chat_messages ADD CONSTRAINT ck_chat_sender_account_uuid_non_nil + CHECK (sender_account_id <> '00000000-0000-0000-0000-000000000000'::uuid); +ALTER TABLE chat_messages ADD CONSTRAINT ck_chat_recipient_account_uuid_non_nil + CHECK (recipient_account_id <> '00000000-0000-0000-0000-000000000000'::uuid); +ALTER TABLE friend_links ADD CONSTRAINT ck_friend_account_uuid_non_nil + CHECK (account_id <> '00000000-0000-0000-0000-000000000000'::uuid); +ALTER TABLE friend_links ADD CONSTRAINT ck_friend_subject_uuid_non_nil + CHECK (friend_account_id <> '00000000-0000-0000-0000-000000000000'::uuid); +ALTER TABLE mail_messages ADD CONSTRAINT ck_mail_sender_account_uuid_non_nil + CHECK (sender_account_id <> '00000000-0000-0000-0000-000000000000'::uuid); +ALTER TABLE mail_messages ADD CONSTRAINT ck_mail_recipient_account_uuid_non_nil + CHECK (recipient_account_id <> '00000000-0000-0000-0000-000000000000'::uuid); +ALTER TABLE account_friend_links ADD CONSTRAINT ck_account_friend_account_uuid_non_nil + CHECK (account_id <> '00000000-0000-0000-0000-000000000000'::uuid); +ALTER TABLE account_friend_links ADD CONSTRAINT ck_account_friend_subject_uuid_non_nil + 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..195bfa886d 100644 --- a/services/social-groups-service/src/main/resources/openapi.yaml +++ b/services/social-groups-service/src/main/resources/openapi.yaml @@ -2,7 +2,7 @@ openapi: 3.0.3 info: title: Social Groups Service API description: >- - API for friend lists and guild chat. Current REST DTOs use Java Long + API for friend lists and guild chat. Account identifiers are canonical lowercase, non-nil UUID strings. Account-bound viewer and sender claims must match the authenticated Account UUID. 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, @@ -29,11 +29,13 @@ components: type: integer format: int64 accountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' friendAccountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' required: - tenantId - accountId @@ -48,11 +50,13 @@ components: type: integer format: int64 accountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' friendAccountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' status: type: string createdAt: @@ -62,8 +66,9 @@ components: type: object properties: friendAccountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' online: type: boolean gameInstanceId: @@ -141,8 +146,9 @@ components: type: integer format: int64 accountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' visibilityPolicy: type: string enum: [PUBLIC, FRIENDS_ONLY, PRIVATE, HIDDEN_STAFF] @@ -162,11 +168,13 @@ components: type: integer format: int64 accountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' friendAccountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' status: type: string createdAt: @@ -236,11 +244,13 @@ components: type: integer format: int64 senderAccountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' recipientAccountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' subject: type: string content: @@ -261,11 +271,13 @@ components: type: integer format: int64 senderAccountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' recipientAccountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' subject: type: string content: @@ -283,16 +295,18 @@ components: type: integer format: int64 senderAccountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' type: type: string enum: [SAY, WHISPER, TELL, GUILD, CITY, ACCOUNT] channelId: type: string recipientAccountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' guildId: type: integer format: int64 @@ -320,10 +334,10 @@ components: those checks. Reuse by another sender or with any changed field is an IDEMPOTENCY_CONFLICT and does not disclose the stored outcome. Current implementation instead deduplicates only by - (tenantId,effectId), trusts the request-body senderAccountId for + (tenantId,effectId), requires the request-body senderAccountId to match the authenticated caller for exact sender identity, and returns the existing row after - route-level SocialAccessGuard access but before authenticated-sender - binding or stable-field validation; see + route-level SocialAccessGuard caller correlation but without binding + the stored replay to that caller or the stable request fields; see design/architecture/microservices/social-groups-service/api-contracts.md#implementation-status. required: - tenantId @@ -340,8 +354,9 @@ components: type: integer format: int64 senderAccountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' content: type: string timestamp: @@ -354,8 +369,9 @@ components: type: integer format: int64 recipientAccountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' type: type: string effectId: @@ -442,8 +458,9 @@ components: type: integer format: int64 ownerAccountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' name: type: string required: @@ -462,8 +479,9 @@ components: name: type: string ownerAccountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' createdAt: type: string format: date-time @@ -474,8 +492,9 @@ components: type: integer format: int64 accountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' channelId: type: string required: @@ -500,8 +519,9 @@ components: type: integer format: int64 accountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' role: type: string required: @@ -519,8 +539,9 @@ components: type: integer format: int64 accountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' role: type: string required: @@ -541,8 +562,9 @@ components: type: integer format: int64 accountId: - type: integer - format: int64 + type: string + format: uuid + pattern: '^(?!00000000-0000-0000-0000-000000000000$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' role: type: string paths: @@ -579,8 +601,8 @@ paths: name: accountId required: true schema: - type: integer - format: int64 + type: string + format: uuid - in: query name: filter required: false @@ -643,8 +665,8 @@ paths: name: friendAccountId required: true schema: - type: integer - format: int64 + type: string + format: uuid - in: query name: tenantId required: true @@ -655,8 +677,8 @@ paths: name: accountId required: true schema: - type: integer - format: int64 + type: string + format: uuid responses: '200': description: Friend roster entry @@ -677,8 +699,8 @@ paths: name: friendAccountId required: true schema: - type: integer - format: int64 + type: string + format: uuid - in: query name: tenantId required: true @@ -689,8 +711,8 @@ paths: name: accountId required: true schema: - type: integer - format: int64 + type: string + format: uuid responses: '200': description: Friend link removed @@ -716,8 +738,8 @@ paths: name: accountId required: true schema: - type: integer - format: int64 + type: string + format: uuid responses: '200': description: Friend roster entry @@ -749,8 +771,8 @@ paths: name: accountId required: true schema: - type: integer - format: int64 + type: string + format: uuid responses: '200': description: Removed friend roster entry @@ -778,8 +800,8 @@ paths: name: accountId required: true schema: - type: integer - format: int64 + type: string + format: uuid responses: '200': description: Friend roster summary @@ -805,8 +827,8 @@ paths: name: accountId required: true schema: - type: integer - format: int64 + type: string + format: uuid - in: query name: filter required: false @@ -854,8 +876,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/SocialGroupsApplicationIntegrationTest.java b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java index 79ff6658bb..c331c6a7bf 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.socialgroups; +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; @@ -115,14 +116,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( @@ -131,7 +132,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, accountUuid(2L))) .thenReturn( java.util.Optional.of( net.firedevops.firemud.socialgroups.dto.FriendPresenceVisibilityPolicyValue @@ -156,10 +157,15 @@ void pingEndpointReturnsPong() throws Exception { @Test void friendRosterRejectsMalformedTenantIdAsInvalidArgument() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(accountUuid(2L)); HttpResponse response = - send(authedGet(token, "http://localhost:" + port + "/friends?tenantId=bad&accountId=2")); + send( + authedGet( + token, + "http://localhost:" + + port + + "/friends?tenantId=bad&accountId=10000000-0000-4000-8000-000000000002")); assertThat(response.statusCode()).isEqualTo(400); assertThat(response.body()).contains("\"code\":\"INVALID_ARGUMENT\""); @@ -168,7 +174,7 @@ void friendRosterRejectsMalformedTenantIdAsInvalidArgument() throws Exception { @Test void friendRosterRejectsMalformedFilterAsInvalidArgument() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(accountUuid(2L)); HttpResponse response = send( @@ -176,7 +182,7 @@ void friendRosterRejectsMalformedFilterAsInvalidArgument() throws Exception { token, "http://localhost:" + port - + "/friends?tenantId=1&accountId=2&filter=NOT_A_FILTER")); + + "/friends?tenantId=1&accountId=10000000-0000-4000-8000-000000000002&filter=NOT_A_FILTER")); assertThat(response.statusCode()).isEqualTo(400); assertThat(response.body()).contains("\"code\":\"INVALID_ARGUMENT\""); @@ -187,7 +193,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, + accountUuid(2L), + ChatType.SAY, + null, + accountUuid(2L), + null, + null, + "hello there", + "fx-comm-42"); ChatMessageDto first = chatService.sendMessage(request); ChatMessageDto replay = chatService.sendMessage(request); @@ -196,14 +210,15 @@ 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:" + accountUuid(2L), 0, -1); List cachedMessages = new ArrayList<>(redisRange == null ? List.of() : redisRange); assertThat(cachedMessages).containsExactly("hello there"); } @Test void friendRosterAndPresenceEndpointsReturnCanonicalEmbeddedPresence() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(accountUuid(2L)); HttpResponse addResponse = send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) @@ -212,18 +227,20 @@ void friendRosterAndPresenceEndpointsReturnCanonicalEmbeddedPresence() throws Ex .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":3} + {"tenantId":1,"accountId":"10000000-0000-4000-8000-000000000002","friendAccountId":"10000000-0000-4000-8000-000000000003"} """)) .build()); assertThat(addResponse.statusCode()).isEqualTo(200); - acceptFriendLink(1L, 2L, 3L); + acceptFriendLink(1L, accountUuid(2L), accountUuid(3L)); - Mockito.when(TEST_GAME_SESSION_CLIENT.queryAccountPresence(1L, 2L, List.of(3L))) + Mockito.when( + TEST_GAME_SESSION_CLIENT.queryAccountPresence( + 1L, accountUuid(2L), List.of(accountUuid(3L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(accountUuid(3L)) .setOnline(true) .setGameInstanceId("9") .setPlayableStateScope( @@ -245,9 +262,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=10000000-0000-4000-8000-000000000002")); assertThat(rosterResponse.statusCode()).isEqualTo(200); - assertThat(rosterResponse.body()).contains("\"friendAccountId\":3"); + assertThat(rosterResponse.body()) + .contains("\"friendAccountId\":\"10000000-0000-4000-8000-000000000003\""); assertThat(rosterResponse.body()).contains("\"status\":\"active\""); assertThat(rosterResponse.body()).contains("\"presence\""); assertThat(rosterResponse.body()).contains("\"characterName\":\"Sora\""); @@ -256,31 +279,45 @@ 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=10000000-0000-4000-8000-000000000002")); assertThat(presenceResponse.statusCode()).isEqualTo(200); - assertThat(presenceResponse.body()).contains("\"friendAccountId\":3"); + assertThat(presenceResponse.body()) + .contains("\"friendAccountId\":\"10000000-0000-4000-8000-000000000003\""); 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/10000000-0000-4000-8000-000000000003?tenantId=1&accountId=10000000-0000-4000-8000-000000000002")); assertThat(detailResponse.statusCode()).isEqualTo(200); assertThat(detailResponse.body()).contains("\"friendLinkId\""); - assertThat(detailResponse.body()).contains("\"friendAccountId\":3"); + assertThat(detailResponse.body()) + .contains("\"friendAccountId\":\"10000000-0000-4000-8000-000000000003\""); 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=10000000-0000-4000-8000-000000000002")); assertThat(ordinalDetailResponse.statusCode()).isEqualTo(200); assertThat(ordinalDetailResponse.body()).contains("\"ordinal\":1"); - assertThat(ordinalDetailResponse.body()).contains("\"friendAccountId\":3"); + assertThat(ordinalDetailResponse.body()) + .contains("\"friendAccountId\":\"10000000-0000-4000-8000-000000000003\""); } @Test void friendRosterEndpointFallsBackToOfflineWhenPresenceIsUnavailable() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(accountUuid(2L)); send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -288,25 +325,33 @@ void friendRosterEndpointFallsBackToOfflineWhenPresenceIsUnavailable() throws Ex .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":3} + {"tenantId":1,"accountId":"10000000-0000-4000-8000-000000000002","friendAccountId":"10000000-0000-4000-8000-000000000003"} """)) .build()); - acceptFriendLink(1L, 2L, 3L); + acceptFriendLink(1L, accountUuid(2L), accountUuid(3L)); - Mockito.when(TEST_GAME_SESSION_CLIENT.queryAccountPresence(1L, 2L, List.of(3L))) + Mockito.when( + TEST_GAME_SESSION_CLIENT.queryAccountPresence( + 1L, accountUuid(2L), List.of(accountUuid(3L)))) .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=10000000-0000-4000-8000-000000000002")); assertThat(rosterResponse.statusCode()).isEqualTo(200); - assertThat(rosterResponse.body()).contains("\"friendAccountId\":3"); + assertThat(rosterResponse.body()) + .contains("\"friendAccountId\":\"10000000-0000-4000-8000-000000000003\""); assertThat(rosterResponse.body()).contains("\"online\":false"); } @Test void friendRosterEndpointSupportsCanonicalOnlineFilter() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(accountUuid(2L)); send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -314,10 +359,10 @@ void friendRosterEndpointSupportsCanonicalOnlineFilter() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":3} + {"tenantId":1,"accountId":"10000000-0000-4000-8000-000000000002","friendAccountId":"10000000-0000-4000-8000-000000000003"} """)) .build()); - acceptFriendLink(1L, 2L, 3L); + acceptFriendLink(1L, accountUuid(2L), accountUuid(3L)); send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -325,37 +370,49 @@ void friendRosterEndpointSupportsCanonicalOnlineFilter() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":4} + {"tenantId":1,"accountId":"10000000-0000-4000-8000-000000000002","friendAccountId":"10000000-0000-4000-8000-000000000004"} """)) .build()); - acceptFriendLink(1L, 2L, 4L); + acceptFriendLink(1L, accountUuid(2L), accountUuid(4L)); - Mockito.when(TEST_GAME_SESSION_CLIENT.queryAccountPresence(1L, 2L, List.of(3L, 4L))) + Mockito.when( + TEST_GAME_SESSION_CLIENT.queryAccountPresence( + 1L, accountUuid(2L), List.of(accountUuid(3L), accountUuid(4L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( - AccountPresenceEntry.newBuilder().setAccountId("3").setOnline(true).build()) + AccountPresenceEntry.newBuilder() + .setAccountId(accountUuid(3L)) + .setOnline(true) + .build()) .addPresences( - AccountPresenceEntry.newBuilder().setAccountId("4").setOnline(false).build()) + AccountPresenceEntry.newBuilder() + .setAccountId(accountUuid(4L)) + .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=10000000-0000-4000-8000-000000000002&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\":\"10000000-0000-4000-8000-000000000003\""); + assertThat(response.body()) + .doesNotContain("\"friendAccountId\":\"10000000-0000-4000-8000-000000000004\""); } @Test void friendRosterEndpointSupportsCanonicalSharedScopeFilter() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(accountUuid(2L)); send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -363,10 +420,10 @@ void friendRosterEndpointSupportsCanonicalSharedScopeFilter() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":3} + {"tenantId":1,"accountId":"10000000-0000-4000-8000-000000000002","friendAccountId":"10000000-0000-4000-8000-000000000003"} """)) .build()); - acceptFriendLink(1L, 2L, 3L); + acceptFriendLink(1L, accountUuid(2L), accountUuid(3L)); send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -374,17 +431,19 @@ void friendRosterEndpointSupportsCanonicalSharedScopeFilter() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":4} + {"tenantId":1,"accountId":"10000000-0000-4000-8000-000000000002","friendAccountId":"10000000-0000-4000-8000-000000000004"} """)) .build()); - acceptFriendLink(1L, 2L, 4L); + acceptFriendLink(1L, accountUuid(2L), accountUuid(4L)); - Mockito.when(TEST_GAME_SESSION_CLIENT.queryAccountPresence(1L, 2L, List.of(3L, 4L))) + Mockito.when( + TEST_GAME_SESSION_CLIENT.queryAccountPresence( + 1L, accountUuid(2L), List.of(accountUuid(3L), accountUuid(4L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(accountUuid(3L)) .setOnline(true) .setPlayableStateScope( net.firedevops.firemud.entitymanagement.v1.PlayableStateScope @@ -392,7 +451,7 @@ void friendRosterEndpointSupportsCanonicalSharedScopeFilter() throws Exception { .build()) .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("4") + .setAccountId(accountUuid(4L)) .setOnline(true) .setPlayableStateScope( net.firedevops.firemud.entitymanagement.v1.PlayableStateScope @@ -404,19 +463,23 @@ void friendRosterEndpointSupportsCanonicalSharedScopeFilter() throws Exception { send( authedGet( token, - "http://localhost:" + port + "/friends?tenantId=1&accountId=2&filter=SHARED")); + "http://localhost:" + + port + + "/friends?tenantId=1&accountId=10000000-0000-4000-8000-000000000002&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\":\"10000000-0000-4000-8000-000000000003\""); + assertThat(response.body()) + .doesNotContain("\"friendAccountId\":\"10000000-0000-4000-8000-000000000004\""); } @Test void friendRosterSummaryEndpointReturnsCanonicalCounts() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(accountUuid(2L)); send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -424,10 +487,10 @@ void friendRosterSummaryEndpointReturnsCanonicalCounts() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":3} + {"tenantId":1,"accountId":"10000000-0000-4000-8000-000000000002","friendAccountId":"10000000-0000-4000-8000-000000000003"} """)) .build()); - acceptFriendLink(1L, 2L, 3L); + acceptFriendLink(1L, accountUuid(2L), accountUuid(3L)); send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -435,19 +498,24 @@ void friendRosterSummaryEndpointReturnsCanonicalCounts() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":4} + {"tenantId":1,"accountId":"10000000-0000-4000-8000-000000000002","friendAccountId":"10000000-0000-4000-8000-000000000004"} """)) .build()); - acceptFriendLink(1L, 2L, 4L); + acceptFriendLink(1L, accountUuid(2L), accountUuid(4L)); - Mockito.when(TEST_GAME_SESSION_CLIENT.queryAccountPresence(1L, 2L, List.of(3L, 4L))) + Mockito.when( + TEST_GAME_SESSION_CLIENT.queryAccountPresence( + 1L, accountUuid(2L), List.of(accountUuid(3L), accountUuid(4L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( - AccountPresenceEntry.newBuilder().setAccountId("3").setOnline(true).build()) + AccountPresenceEntry.newBuilder() + .setAccountId(accountUuid(3L)) + .setOnline(true) + .build()) .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("4") + .setAccountId(accountUuid(4L)) .setOnline(false) .setLastSeenAtMs(1_744_353_730_000L) .build()) @@ -456,7 +524,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=10000000-0000-4000-8000-000000000002")); assertThat(response.statusCode()).isEqualTo(200); assertThat(response.body()).contains("\"totalCount\":2"); @@ -472,85 +543,142 @@ void friendRosterSummaryEndpointReturnsCanonicalCounts() throws Exception { @Test void friendEndpointsRequireReciprocalActiveLinksWithinRequestedTenant() throws Exception { - String token = privilegedAccountToken(2L); - 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"); + String token = privilegedAccountToken(accountUuid(2L)); + saveFriendLink(1L, accountUuid(2L), accountUuid(3L), "active"); + saveFriendLink(1L, accountUuid(2L), accountUuid(4L), "active"); + saveFriendLink(1L, accountUuid(4L), accountUuid(2L), "inactive"); + saveFriendLink(1L, accountUuid(2L), accountUuid(5L), "active"); + saveFriendLink(1L, accountUuid(5L), accountUuid(2L), "active"); HttpResponse tenantOneRoster = - send(authedGet(token, "http://localhost:" + port + "/friends?tenantId=1&accountId=2")); + send( + authedGet( + token, + "http://localhost:" + + port + + "/friends?tenantId=1&accountId=10000000-0000-4000-8000-000000000002")); 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\":\"10000000-0000-4000-8000-000000000005\""); + assertThat(tenantOneRoster.body()) + .doesNotContain("\"friendAccountId\":\"10000000-0000-4000-8000-000000000003\""); + assertThat(tenantOneRoster.body()) + .doesNotContain("\"friendAccountId\":\"10000000-0000-4000-8000-000000000004\""); HttpResponse tenantOnePresence = send( authedGet( - token, "http://localhost:" + port + "/friends/presence?tenantId=1&accountId=2")); + token, + "http://localhost:" + + port + + "/friends/presence?tenantId=1&accountId=10000000-0000-4000-8000-000000000002")); 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\":\"10000000-0000-4000-8000-000000000005\""); + assertThat(tenantOnePresence.body()) + .doesNotContain("\"friendAccountId\":\"10000000-0000-4000-8000-000000000003\""); + assertThat(tenantOnePresence.body()) + .doesNotContain("\"friendAccountId\":\"10000000-0000-4000-8000-000000000004\""); HttpResponse reciprocalDetail = - send(authedGet(token, "http://localhost:" + port + "/friends/5?tenantId=1&accountId=2")); + send( + authedGet( + token, + "http://localhost:" + + port + + "/friends/10000000-0000-4000-8000-000000000005?tenantId=1&accountId=10000000-0000-4000-8000-000000000002")); assertThat(reciprocalDetail.statusCode()).isEqualTo(200); - assertThat(reciprocalDetail.body()).contains("\"friendAccountId\":5"); + assertThat(reciprocalDetail.body()) + .contains("\"friendAccountId\":\"10000000-0000-4000-8000-000000000005\""); 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=10000000-0000-4000-8000-000000000002")); assertThat(reciprocalOrdinal.statusCode()).isEqualTo(200); - assertThat(reciprocalOrdinal.body()).contains("\"friendAccountId\":5"); + assertThat(reciprocalOrdinal.body()) + .contains("\"friendAccountId\":\"10000000-0000-4000-8000-000000000005\""); HttpResponse tenantOneSummary = send( authedGet( - token, "http://localhost:" + port + "/friends/summary?tenantId=1&accountId=2")); + token, + "http://localhost:" + + port + + "/friends/summary?tenantId=1&accountId=10000000-0000-4000-8000-000000000002")); 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/10000000-0000-4000-8000-000000000003?tenantId=1&accountId=10000000-0000-4000-8000-000000000002")); 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/10000000-0000-4000-8000-000000000004?tenantId=1&accountId=10000000-0000-4000-8000-000000000002")); 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=10000000-0000-4000-8000-000000000002")); 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=10000000-0000-4000-8000-000000000002")); assertThat(wrongTenantPresence.statusCode()).isEqualTo(200); - assertThat(wrongTenantPresence.body()).doesNotContain("\"friendAccountId\":5"); + assertThat(wrongTenantPresence.body()) + .doesNotContain("\"friendAccountId\":\"10000000-0000-4000-8000-000000000005\""); HttpResponse wrongTenantDetail = - send(authedGet(token, "http://localhost:" + port + "/friends/5?tenantId=2&accountId=2")); + send( + authedGet( + token, + "http://localhost:" + + port + + "/friends/10000000-0000-4000-8000-000000000005?tenantId=2&accountId=10000000-0000-4000-8000-000000000002")); 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=10000000-0000-4000-8000-000000000002")); 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=10000000-0000-4000-8000-000000000002")); assertThat(wrongTenantSummary.statusCode()).isEqualTo(200); assertThat(wrongTenantSummary.body()).contains("\"totalCount\":0"); } @Test void addFriendIsIdempotentForExistingActiveAccountLink() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(accountUuid(2L)); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -558,7 +686,7 @@ void addFriendIsIdempotentForExistingActiveAccountLink() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":3} + {"tenantId":1,"accountId":"10000000-0000-4000-8000-000000000002","friendAccountId":"10000000-0000-4000-8000-000000000003"} """)) .build(); @@ -567,24 +695,26 @@ void addFriendIsIdempotentForExistingActiveAccountLink() throws Exception { assertThat(firstResponse.statusCode()).isEqualTo(200); assertThat(secondResponse.statusCode()).isEqualTo(200); - assertThat(accountFriendLinkRepository.findByTenantIdAndAccountIdAndStatus(1L, 2L, "active")) + assertThat( + accountFriendLinkRepository.findByTenantIdAndAccountIdAndStatus( + 1L, accountUuid(2L), "active")) .hasSize(1); assertThat( accountFriendLinkRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( - 1L, 2L, "active")) + 1L, accountUuid(2L), "active")) .isEmpty(); - acceptFriendLink(1L, 2L, 3L); + acceptFriendLink(1L, accountUuid(2L), accountUuid(3L)); assertThat( accountFriendLinkRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( - 1L, 2L, "active")) + 1L, accountUuid(2L), "active")) .hasSize(1); } @Test void addFriendRejectsSelfLink() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(accountUuid(2L)); HttpResponse response = send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) @@ -593,19 +723,21 @@ void addFriendRejectsSelfLink() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":2} + {"tenantId":1,"accountId":"10000000-0000-4000-8000-000000000002","friendAccountId":"10000000-0000-4000-8000-000000000002"} """)) .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, accountUuid(2L), "active")) .isEmpty(); } @Test void removeFriendDeletesExistingActiveAccountLinkAndIsIdempotent() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(accountUuid(2L)); HttpRequest addRequest = HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -613,7 +745,7 @@ void removeFriendDeletesExistingActiveAccountLinkAndIsIdempotent() throws Except .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":3} + {"tenantId":1,"accountId":"10000000-0000-4000-8000-000000000002","friendAccountId":"10000000-0000-4000-8000-000000000003"} """)) .build(); @@ -622,27 +754,35 @@ 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/10000000-0000-4000-8000-000000000003?tenantId=1&accountId=10000000-0000-4000-8000-000000000002")) .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/10000000-0000-4000-8000-000000000003?tenantId=1&accountId=10000000-0000-4000-8000-000000000002")) .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, accountUuid(2L), "active")) .isEmpty(); } @Test void removeFriendByOrdinalDeletesCanonicalRosterEntry() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(accountUuid(2L)); send( HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/friends")) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -650,35 +790,43 @@ void removeFriendByOrdinalDeletesCanonicalRosterEntry() throws Exception { .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"friendAccountId":3} + {"tenantId":1,"accountId":"10000000-0000-4000-8000-000000000002","friendAccountId":"10000000-0000-4000-8000-000000000003"} """)) .build()); - acceptFriendLink(1L, 2L, 3L); + acceptFriendLink(1L, accountUuid(2L), accountUuid(3L)); 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=10000000-0000-4000-8000-000000000002")) .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\":\"10000000-0000-4000-8000-000000000003\""); + assertThat( + accountFriendLinkRepository.findByTenantIdAndAccountIdAndStatus( + 1L, accountUuid(2L), "active")) .isEmpty(); } @Test void friendVisibilityEndpointsExposeCanonicalPolicyReadAndWrite() throws Exception { - String token = privilegedAccountToken(2L); + String token = privilegedAccountToken(accountUuid(2L)); HttpResponse getResponse = send( authedGet( - token, "http://localhost:" + port + "/friends/visibility?tenantId=1&accountId=2")); + token, + "http://localhost:" + + port + + "/friends/visibility?tenantId=1&accountId=10000000-0000-4000-8000-000000000002")); assertThat(getResponse.statusCode()).isEqualTo(200); assertThat(getResponse.body()).contains("\"currentPolicy\":\"FRIENDS_ONLY\""); @@ -686,7 +834,7 @@ void friendVisibilityEndpointsExposeCanonicalPolicyReadAndWrite() throws Excepti Mockito.when( TEST_ACCOUNT_CLIENT.updatePresenceVisibilityPolicy( 1L, - 2L, + accountUuid(2L), net.firedevops.firemud.socialgroups.dto.FriendPresenceVisibilityPolicyValue .PRIVATE)) .thenReturn(true); @@ -699,7 +847,7 @@ void friendVisibilityEndpointsExposeCanonicalPolicyReadAndWrite() throws Excepti .PUT( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"visibilityPolicy":"PRIVATE"} + {"tenantId":1,"accountId":"10000000-0000-4000-8000-000000000002","visibilityPolicy":"PRIVATE"} """)) .build()); @@ -714,7 +862,7 @@ 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); @@ -724,7 +872,8 @@ private void acceptFriendLink(long tenantId, long accountId, long friendAccountI 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); @@ -734,11 +883,11 @@ private void saveFriendLink(long tenantId, long accountId, long friendAccountId, accountFriendLinkRepository.save(link); } - private static String privilegedAccountToken(long accountId) { + private static String privilegedAccountToken(String accountId) { return JWT_UTIL.generateToken( - Long.toString(accountId), + accountId, Map.of( - "accountId", Long.toString(accountId), + "accountId", accountId, "globalRoles", List.of("platformAdmin"), "scopedRoles", Map.of("1", List.of("tenantAdmin")))); } diff --git a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialAccountUuidMigrationPostgresIntegrationTest.java b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialAccountUuidMigrationPostgresIntegrationTest.java new file mode 100644 index 0000000000..ebbc2b04bd --- /dev/null +++ b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialAccountUuidMigrationPostgresIntegrationTest.java @@ -0,0 +1,277 @@ +package integration.net.firedevops.firemud.socialgroups.repository; + +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.socialgroups.entity.AccountFriendLink; +import net.firedevops.firemud.socialgroups.entity.ChatMessage; +import net.firedevops.firemud.socialgroups.entity.Guild; +import net.firedevops.firemud.socialgroups.entity.GuildMember; +import net.firedevops.firemud.socialgroups.entity.MailMessage; +import net.firedevops.firemud.socialgroups.enums.ChatType; +import net.firedevops.firemud.socialgroups.repository.AccountFriendLinkRepository; +import net.firedevops.firemud.socialgroups.repository.ChatMessageRepository; +import net.firedevops.firemud.socialgroups.repository.GuildMemberRepository; +import net.firedevops.firemud.socialgroups.repository.GuildRepository; +import net.firedevops.firemud.socialgroups.repository.MailMessageRepository; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.CloseableDSLContext; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Physical PostgreSQL migration and generated-jOOQ proof; no mocked SQL success. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class SocialAccountUuidMigrationPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private static final List ACCOUNT_TABLES = + List.of( + "guilds", + "guild_members", + "chat_messages", + "friend_links", + "mail_messages", + "account_friend_links"); + + @Test + void emptyLegacyFrontierConvergesAndTypedRepositoriesRoundTripCanonicalAccountUuids() { + String schema = schema(); + migrate(schema, "9"); + migrate(schema, "10"); + try (var dsl = database(schema)) { + assertThat( + dsl.fetch( + "SELECT data_type FROM information_schema.columns WHERE table_schema = ? " + + "AND column_name IN ('account_id', 'friend_account_id', 'owner_account_id', 'sender_account_id', 'recipient_account_id')", + schema) + .getValues(0, String.class)) + .hasSize(10) + .containsOnly("uuid"); + assertThat( + dsl.fetch( + "SELECT data_type FROM information_schema.columns WHERE table_schema = ? " + + "AND column_name IN ('id', 'tenant_id', 'guild_id', 'city_id')", + schema) + .getValues(0, String.class)) + .containsOnly("bigint"); + + Guild guild = new Guild(); + guild.setTenantId(7L); + guild.setName("UUID guild"); + guild.setOwnerAccountId(accountUuid(1L)); + guild.setCreatedAt(Instant.parse("2026-10-30T00:00:00Z")); + GuildRepository guilds = new GuildRepository(dsl); + guilds.save(guild); + guild.setName("Updated UUID guild"); + assertThat(guilds.save(guild).getOwnerAccountId()).isEqualTo(accountUuid(1L)); + + GuildMember member = new GuildMember(); + member.setTenantId(7L); + member.setGuildId(guild.getId()); + member.setAccountId(accountUuid(2L)); + member.setRole("member"); + GuildMemberRepository members = new GuildMemberRepository(dsl); + members.save(member); + assertThat( + members.findFirstByTenantIdAndGuildIdAndAccountId(7L, guild.getId(), accountUuid(2L))) + .isPresent() + .get() + .extracting(GuildMember::getAccountId) + .isEqualTo(accountUuid(2L)); + + AccountFriendLinkRepository friends = new AccountFriendLinkRepository(dsl); + friends.save(link(accountUuid(1L), accountUuid(2L))); + assertThat( + friends.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 7L, accountUuid(1L), "active")) + .isEmpty(); + friends.save(link(accountUuid(2L), accountUuid(1L))); + assertThat( + friends.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 7L, accountUuid(1L), "active")) + .extracting(AccountFriendLink::getFriendAccountId) + .containsExactly(accountUuid(2L)); + assertThat( + friends.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 8L, accountUuid(1L), "active")) + .isEmpty(); + friends.save(link(accountUuid(1L), accountUuid(3L))); + var account = + org.mockito.Mockito.mock(net.firedevops.firemud.socialgroups.client.AccountClient.class); + var presence = + org.mockito.Mockito.mock( + net.firedevops.firemud.socialgroups.client.GameSessionClient.class); + org.mockito.Mockito.when(account.getPresenceVisibilityPolicies(7L, List.of(accountUuid(2L)))) + .thenReturn( + Map.of( + accountUuid(2L), + net.firedevops.firemud.socialgroups.dto.FriendPresenceVisibilityPolicyValue + .PRIVATE)); + var friendService = + new net.firedevops.firemud.socialgroups.service.impl.FriendServiceImpl( + friends, presence, account); + assertThat(friendService.getFriend(7L, accountUuid(1L), accountUuid(3L))).isEmpty(); + var roster = friendService.listFriends(7L, accountUuid(1L)); + assertThat(roster.friends()).hasSize(1); + assertThat(roster.friends().getFirst().friendAccountId()).isEqualTo(accountUuid(2L)); + assertThat(roster.friends().getFirst().presence().visibilityPolicy()).isNull(); + assertThat(roster.friends().getFirst().presence().lastSeenAt()).isNull(); + assertThat(roster.friends().getFirst().presence().online()).isFalse(); + org.mockito.Mockito.verifyNoInteractions(presence); + + ChatMessage message = new ChatMessage(); + message.setTenantId(7L); + message.setSenderAccountId(accountUuid(1L)); + message.setRecipientAccountId(accountUuid(2L)); + message.setContent("ordinary account message"); + message.setTimestamp(Instant.now()); + message.setEffectId("uuid-message"); + message.setType(ChatType.TELL); + ChatMessageRepository chat = new ChatMessageRepository(dsl); + chat.save(message); + assertThat(chat.findByTenantIdAndEffectId(7L, "uuid-message")) + .isPresent() + .get() + .extracting(ChatMessage::getSenderAccountId, ChatMessage::getRecipientAccountId) + .containsExactly(accountUuid(1L), accountUuid(2L)); + message.setRecipientAccountId(null); + assertThat(chat.save(message).getRecipientAccountId()).isNull(); + + MailMessage mail = new MailMessage(); + mail.setTenantId(7L); + mail.setSenderAccountId(accountUuid(1L)); + mail.setRecipientAccountId(accountUuid(2L)); + mail.setSubject("subject"); + mail.setContent("body"); + mail.setSentAt(Instant.now()); + MailMessageRepository mails = new MailMessageRepository(dsl); + mails.save(mail); + assertThat(mails.save(mail).getRecipientAccountId()).isEqualTo(accountUuid(2L)); + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO friend_links (tenant_id, account_id, friend_account_id, status) VALUES (7, ?::uuid, ?::uuid, 'active')", + "00000000-0000-0000-0000-000000000000", + accountUuid(2L))) + .hasMessageContaining("ck_friend_account_uuid_non_nil"); + assertThatThrownBy( + () -> members.findFirstByTenantIdAndGuildIdAndAccountId(7L, guild.getId(), "2")) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @ParameterizedTest + @ValueSource( + strings = { + "guilds", + "guild_members", + "chat_messages", + "friend_links", + "mail_messages", + "account_friend_links" + }) + void anyRetainedLegacyAccountReferenceRefusesBeforeDdlAndPreservesAllRowImages(String table) { + String schema = schema(); + migrate(schema, "9"); + try (var dsl = database(schema)) { + switch (table) { + case "guilds" -> + dsl.execute( + "INSERT INTO guilds (id, tenant_id, name, owner_account_id) VALUES (11, 7, 'retained', 101)"); + case "guild_members" -> { + dsl.execute( + "INSERT INTO guilds (id, tenant_id, name, owner_account_id) VALUES (11, 7, 'retained', 101)"); + dsl.execute( + "INSERT INTO guild_members (tenant_id, guild_id, account_id, role) VALUES (7, 11, 102, 'member')"); + } + case "chat_messages" -> + dsl.execute( + "INSERT INTO chat_messages (tenant_id, sender_account_id, recipient_account_id, content) VALUES (7, 101, 102, 'retained chat')"); + case "friend_links", "account_friend_links" -> + dsl.execute( + "INSERT INTO " + + table + + " (tenant_id, account_id, friend_account_id, status) VALUES (7, 101, 102, 'active')"); + case "mail_messages" -> + dsl.execute( + "INSERT INTO mail_messages (tenant_id, sender_account_id, recipient_account_id, subject, content) VALUES (7, 101, 102, 'retained', 'mail')"); + default -> throw new AssertionError(table); + } + Map> before = rowImages(dsl); + assertThatThrownBy(() -> migrate(schema, "10")) + .hasStackTraceContaining("SOCIAL_ACCOUNT_UUID_MIGRATION_BLOCKED"); + assertThat(rowImages(dsl)).isEqualTo(before); + assertThat( + dsl.fetch( + "SELECT data_type FROM information_schema.columns WHERE table_schema = ? " + + "AND column_name IN ('account_id', 'friend_account_id', 'owner_account_id', 'sender_account_id', 'recipient_account_id')", + schema) + .getValues(0, String.class)) + .hasSize(10) + .containsOnly("bigint"); + assertThat(dsl.fetchCount(DSL.table("flyway_schema_history"), DSL.field("version").eq("10"))) + .isZero(); + } + } + + private static AccountFriendLink link(String account, String friend) { + AccountFriendLink link = new AccountFriendLink(); + link.setTenantId(7L); + link.setAccountId(account); + link.setFriendAccountId(friend); + link.setStatus("active"); + link.setCreatedAt(Instant.now()); + return link; + } + + private static Map> rowImages(DSLContext dsl) { + Map> result = new LinkedHashMap<>(); + for (String table : ACCOUNT_TABLES) { + result.put( + table, + dsl.fetch("SELECT row_to_json(t)::text FROM " + table + " t ORDER BY id") + .getValues(0, String.class)); + } + return result; + } + + private static String schema() { + return "social_account_uuid_" + UUID.randomUUID().toString().replace("-", ""); + } + + private static void migrate(String schema, String target) { + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .locations("classpath:db/migration") + .target(target) + .load() + .migrate(); + } + + private static CloseableDSLContext database(String schema) { + CloseableDSLContext dsl = + DSL.using(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + dsl.configuration().set(SQLDialect.POSTGRES); + dsl.execute("SET search_path TO " + schema); + return dsl; + } +} 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..791f4d9606 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,5 +1,6 @@ package net.firedevops.firemud.socialgroups.client; +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -25,6 +26,7 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.socialgroups.dto.FriendPresenceVisibilityPolicyValue; +import net.firedevops.firemud.socialgroups.test.AccountUuidFixtures; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -52,15 +54,16 @@ void batchesPresenceVisibilityPolicyReadsAtTheAccountServiceLimit() throws Excep .build(); }); AccountClient client = newClient(stub); - List accountIds = LongStream.rangeClosed(1L, 101L).boxed().toList(); + List accountIds = + LongStream.rangeClosed(1L, 101L).mapToObj(AccountUuidFixtures::accountUuid).toList(); - Map policies = + Map policies = client.getPresenceVisibilityPolicies(11L, accountIds); assertThat(policies) .hasSize(101) - .containsEntry(1L, FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY) - .containsEntry(101L, FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY); + .containsEntry(accountUuid(1L), FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY) + .containsEntry(accountUuid(101L), FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY); ArgumentCaptor requests = ArgumentCaptor.forClass(ListPresenceVisibilityPoliciesRequest.class); verify(stub, times(2)).listPresenceVisibilityPolicies(requests.capture()); @@ -113,11 +116,119 @@ 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(accountUuid(1L)))).isEmpty(); assertThat(meterRegistry.counter("grpc.app_error", "code", "UNAVAILABLE").count()) .isEqualTo(1.0d); } + @Test + void malformedDuplicateAndUnrequestedPolicySubjectsRedactTheWholeRead() throws Exception { + for (String subject : List.of("2", accountUuid(99L), accountUuid(1L))) { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.listPresenceVisibilityPolicies(any())) + .thenReturn( + ListPresenceVisibilityPoliciesResponse.newBuilder() + .addPolicies( + PresenceVisibilityPolicyEntry.newBuilder() + .setAccountId(accountUuid(1L)) + .setPolicy("PUBLIC")) + .addPolicies( + PresenceVisibilityPolicyEntry.newBuilder() + .setAccountId(subject) + .setPolicy("PUBLIC")) + .build()); + assertThat(newClient(stub).getPresenceVisibilityPolicies(11L, List.of(accountUuid(1L)))) + .isEmpty(); + } + } + + @Test + void laterPolicyChunkFailureRedactsEarlierSuccessfulChunks() throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.listPresenceVisibilityPolicies(any())) + .thenReturn( + ListPresenceVisibilityPoliciesResponse.newBuilder() + .addPolicies( + PresenceVisibilityPolicyEntry.newBuilder() + .setAccountId(accountUuid(1L)) + .setPolicy("PUBLIC")) + .build(), + ListPresenceVisibilityPoliciesResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("UNAVAILABLE").setMessage("unavailable")) + .build()); + assertThat( + newClient(stub) + .getPresenceVisibilityPolicies( + 11L, + LongStream.rangeClosed(1L, 101L) + .mapToObj(AccountUuidFixtures::accountUuid) + .toList())) + .isEmpty(); + } + + @Test + void profileReadRequiresExactCanonicalRequestedAccountAndTenant() throws Exception { + for (String json : + List.of( + "{\"tenantId\":11,\"accountId\":2,\"presenceVisibilityPolicy\":\"PUBLIC\"}", + "{\"tenantId\":11,\"accountId\":\"" + + accountUuid(99L) + + "\",\"presenceVisibilityPolicy\":\"PUBLIC\"}", + "{\"tenantId\":12,\"accountId\":\"" + + accountUuid(1L) + + "\",\"presenceVisibilityPolicy\":\"PUBLIC\"}", + "{\"tenantId\":11,\"presenceVisibilityPolicy\":\"PUBLIC\"}")) { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.getProfile(any())) + .thenReturn( + net.firedevops.firemud.account.v1.GetProfileResponse.newBuilder() + .setProfileJson(json) + .build()); + var client = newClient(stub); + assertThat(client.getPresenceVisibilityPolicy(11L, accountUuid(1L))).isEmpty(); + assertThat( + client.updatePresenceVisibilityPolicy( + 11L, accountUuid(1L), FriendPresenceVisibilityPolicyValue.PUBLIC)) + .isFalse(); + org.mockito.Mockito.verify(stub, org.mockito.Mockito.never()).updateProfile(any()); + } + } + + @Test + void missingPersistedProfilePolicyStaysPrivateAndCanonicalSelfUpdatePreservesProfile() + throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.getProfile(any())) + .thenReturn( + net.firedevops.firemud.account.v1.GetProfileResponse.newBuilder() + .setProfileJson( + "{\"tenantId\":11,\"accountId\":\"" + + accountUuid(1L) + + "\",\"displayName\":\"Name\",\"bio\":\"Bio\"}") + .build()); + when(stub.updateProfile(any())) + .thenReturn( + net.firedevops.firemud.account.v1.UpdateProfileResponse.newBuilder() + .setSuccess(true) + .build()); + var client = newClient(stub); + assertThat(client.getPresenceVisibilityPolicy(11L, accountUuid(1L))) + .contains(FriendPresenceVisibilityPolicyValue.PRIVATE); + assertThat( + client.updatePresenceVisibilityPolicy( + 11L, accountUuid(1L), FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY)) + .isTrue(); + var request = + ArgumentCaptor.forClass(net.firedevops.firemud.account.v1.UpdateProfileRequest.class); + verify(stub).updateProfile(request.capture()); + assertThat(request.getValue().getAccountId()).isEqualTo(accountUuid(1L)); + assertThat(request.getValue().getProfileJson()).contains("Name", "Bio", "FRIENDS_ONLY"); + } + 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..de78a0acbc 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.socialgroups.client; +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -52,7 +53,8 @@ void clearSessionContext() { @Test void loggingAdminClientUsesInternalIdentityEvenWithEndUserContext() { - SessionContext.setContext("42", List.of("player"), Map.of("7", List.of("tenantAdmin"))); + SessionContext.setContext( + accountUuid(42L), List.of("player"), Map.of("7", List.of("tenantAdmin"))); CapturingChannel channel = new CapturingChannel(); LoggingAdminClient client = new LoggingAdminClient( @@ -69,7 +71,8 @@ void loggingAdminClientUsesInternalIdentityEvenWithEndUserContext() { @Test void moderationPolicyClientUsesInternalIdentityEvenWithEndUserContext() { - SessionContext.setContext("42", List.of("player"), Map.of("7", List.of("tenantAdmin"))); + SessionContext.setContext( + accountUuid(42L), List.of("player"), Map.of("7", List.of("tenantAdmin"))); CapturingChannel channel = new CapturingChannel(); ModerationPolicyClient client = new ModerationPolicyClient( @@ -125,7 +128,7 @@ void loggingAdminClientPropagatesApplicationErrors() throws Exception { runtimeIdentityProvider()); client.init(); - assertThatThrownBy(() -> client.reportChatViolation(7L, 42L, "Filtered profanity")) + assertThatThrownBy(() -> client.reportChatViolation(7L, accountUuid(42L), "Filtered profanity")) .isInstanceOf(IllegalStateException.class) .hasMessage("Chat violation report failed: UNAVAILABLE: Report creation unavailable") .hasMessageNotContaining("Filtered profanity"); 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 996c931921..c49c621426 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.socialgroups.controller; +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; 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; @@ -40,10 +41,12 @@ class ChatControllerTest { @Test void sendMessageRejectsZeroTenantIdBeforeAccessCheckAndDispatch() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); String body = """ - {"tenantId":0,"senderAccountId":2,"type":"SAY","content":"hello"} + {"tenantId":0,"senderAccountId":"10000000-0000-4000-8000-000000000002","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 af35da1c08..4c42477ea3 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.socialgroups.controller; +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; @@ -54,11 +55,14 @@ 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, accountUuid(2L), accountUuid(3L)); + FriendLinkDto response = + new FriendLinkDto(1L, 1L, accountUuid(2L), accountUuid(3L), "active", null); when(friendService.addFriend(request)).thenReturn(response); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( post("/friends") @@ -67,17 +71,19 @@ 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(accountUuid(2L))); } @Test void addFriendRejectsSelfLinkAsBadRequest() throws Exception { - AddFriendRequest request = new AddFriendRequest(1L, 2L, 2L); + AddFriendRequest request = new AddFriendRequest(1L, accountUuid(2L), accountUuid(2L)); when(friendService.addFriend(request)) .thenThrow( new IllegalArgumentException("Cannot add or remove your own account as a friend")); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( post("/friends") @@ -93,8 +99,10 @@ void addFriendRejectsSelfLinkAsBadRequest() throws Exception { @Test void addFriendRejectsZeroTenantIdBeforeAccessCheck() throws Exception { - AddFriendRequest request = new AddFriendRequest(0L, 2L, 3L); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + AddFriendRequest request = new AddFriendRequest(0L, accountUuid(2L), accountUuid(3L)); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( @@ -112,12 +120,14 @@ void addFriendRejectsZeroTenantIdBeforeAccessCheck() throws Exception { @Test void removeFriendReturnsSuccess() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( - delete("/friends/3") + delete("/friends/10000000-0000-4000-8000-000000000003") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", accountUuid(2L)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")); @@ -125,17 +135,19 @@ void removeFriendReturnsSuccess() throws Exception { @Test void removeFriendRejectsSelfLinkAsBadRequest() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); org.mockito.Mockito.doThrow( new IllegalArgumentException("Cannot add or remove your own account as a friend")) .when(friendService) - .removeFriend(1L, 2L, 2L); + .removeFriend(1L, accountUuid(2L), accountUuid(2L)); mockMvc .perform( - delete("/friends/2") + delete("/friends/10000000-0000-4000-8000-000000000002") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", accountUuid(2L)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.status").value("ERROR")) @@ -146,36 +158,38 @@ void removeFriendRejectsSelfLinkAsBadRequest() throws Exception { @Test void removeFriendRejectsMalformedFriendAccountIdBeforeAccessCheck() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( delete("/friends/not-a-number") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", accountUuid(2L)) .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, accountUuid(2L), accountUuid(3L))) .thenReturn( java.util.Optional.of( new FriendRosterEntryDto( 1, 7L, 1L, - 2L, - 3L, + accountUuid(2L), + accountUuid(3L), "active", java.time.Instant.parse("2026-04-10T01:02:03Z"), new FriendPresenceDto( - 3L, + accountUuid(3L), true, 9L, "SHARED", @@ -190,35 +204,37 @@ void getFriendReturnsCanonicalRosterEntry() throws Exception { null, null)))); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( - get("/friends/3") + get("/friends/10000000-0000-4000-8000-000000000003") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", accountUuid(2L)) .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(accountUuid(3L))) .andExpect(jsonPath("$.data.presence.characterName").value("Ben")); } @Test void getFriendByOrdinalReturnsCanonicalRosterEntry() throws Exception { - when(friendService.getFriendByOrdinal(1L, 2L, 1)) + when(friendService.getFriendByOrdinal(1L, accountUuid(2L), 1)) .thenReturn( java.util.Optional.of( new FriendRosterEntryDto( 1, 7L, 1L, - 2L, - 3L, + accountUuid(2L), + accountUuid(3L), "active", java.time.Instant.parse("2026-04-10T01:02:03Z"), new FriendPresenceDto( - 3L, + accountUuid(3L), true, 9L, "SHARED", @@ -233,28 +249,32 @@ void getFriendByOrdinalReturnsCanonicalRosterEntry() throws Exception { null, null)))); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( get("/friends/entry/1") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", accountUuid(2L)) .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(accountUuid(3L))); } @Test void getFriendByOrdinalRejectsMalformedOrdinalBeforeAccessCheck() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( get("/friends/entry/not-a-number") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", accountUuid(2L)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) @@ -266,7 +286,9 @@ void getFriendByOrdinalRejectsMalformedOrdinalBeforeAccessCheck() throws Excepti @Test void listFriendPresenceReturnsPresenceList() throws Exception { when(friendService.listFriendPresence( - 1L, 2L, net.firedevops.firemud.socialgroups.dto.FriendRosterFilter.FRIENDS_ONLY)) + 1L, + accountUuid(2L), + net.firedevops.firemud.socialgroups.dto.FriendRosterFilter.FRIENDS_ONLY)) .thenReturn( new net.firedevops.firemud.socialgroups.dto.FriendPresenceViewDto( net.firedevops.firemud.socialgroups.dto.FriendRosterFilter.FRIENDS_ONLY, @@ -274,7 +296,7 @@ void listFriendPresenceReturnsPresenceList() throws Exception { 1, List.of( new FriendPresenceDto( - 3L, + accountUuid(3L), true, 9L, "demo", @@ -287,12 +309,14 @@ void listFriendPresenceReturnsPresenceList() throws Exception { null, null)))); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( get("/friends/presence") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", accountUuid(2L)) .param("filter", "FRIENDS_ONLY") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) @@ -300,7 +324,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(accountUuid(3L))) .andExpect(jsonPath("$.data.presences[0].online").value(true)) .andExpect(jsonPath("$.data.presences[0].worldSlug").value("demo")) .andExpect(jsonPath("$.data.presences[0].realmSlug").value("production")); @@ -308,15 +332,17 @@ void listFriendPresenceReturnsPresenceList() throws Exception { @Test void getFriendPresencePolicyReturnsCanonicalPolicy() throws Exception { - when(friendService.getFriendPresencePolicy(1L, 2L)) + when(friendService.getFriendPresencePolicy(1L, accountUuid(2L))) .thenReturn(new FriendPresencePolicyViewDto(FriendPresenceVisibilityPolicyValue.PRIVATE)); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( get("/friends/visibility") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", accountUuid(2L)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) @@ -325,7 +351,9 @@ void getFriendPresencePolicyReturnsCanonicalPolicy() throws Exception { @Test void getFriendPresencePolicyRejectsMalformedAccountIdBeforeAccessCheck() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( @@ -335,7 +363,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); } @@ -344,13 +372,15 @@ void getFriendPresencePolicyRejectsMalformedAccountIdBeforeAccessCheck() throws void updateFriendPresencePolicyReturnsCanonicalPolicy() throws Exception { UpdateFriendPresencePolicyRequest request = new UpdateFriendPresencePolicyRequest( - 1L, 2L, FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY); + 1L, accountUuid(2L), FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY); when(friendService.updateFriendPresencePolicy( - 1L, 2L, FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY)) + 1L, accountUuid(2L), FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY)) .thenReturn( new FriendPresencePolicyViewDto(FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY)); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( put("/friends/visibility") @@ -366,14 +396,16 @@ void updateFriendPresencePolicyReturnsCanonicalPolicy() throws Exception { void updateFriendPresencePolicyRejectsReservedHiddenStaff() throws Exception { UpdateFriendPresencePolicyRequest request = new UpdateFriendPresencePolicyRequest( - 1L, 2L, FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF); + 1L, accountUuid(2L), FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF); when(friendService.updateFriendPresencePolicy( - 1L, 2L, FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF)) + 1L, accountUuid(2L), FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF)) .thenThrow( new IllegalArgumentException( "Friend presence visibility policy HIDDEN_STAFF is reserved")); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( put("/friends/visibility") @@ -390,7 +422,9 @@ void updateFriendPresencePolicyRejectsReservedHiddenStaff() throws Exception { @Test void listFriendsReturnsRosterList() throws Exception { when(friendService.listFriends( - 1L, 2L, net.firedevops.firemud.socialgroups.dto.FriendRosterFilter.FRIENDS_ONLY)) + 1L, + accountUuid(2L), + net.firedevops.firemud.socialgroups.dto.FriendRosterFilter.FRIENDS_ONLY)) .thenReturn( new net.firedevops.firemud.socialgroups.dto.FriendRosterViewDto( net.firedevops.firemud.socialgroups.dto.FriendRosterFilter.FRIENDS_ONLY, @@ -401,12 +435,12 @@ void listFriendsReturnsRosterList() throws Exception { 1, 7L, 1L, - 2L, - 3L, + accountUuid(2L), + accountUuid(3L), "active", java.time.Instant.parse("2026-04-10T01:02:03Z"), new FriendPresenceDto( - 3L, + accountUuid(3L), true, 9L, "SHARED", @@ -421,12 +455,14 @@ void listFriendsReturnsRosterList() throws Exception { null, null))))); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( get("/friends") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", accountUuid(2L)) .param("filter", "FRIENDS_ONLY") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) @@ -434,7 +470,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(accountUuid(3L))) .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")); @@ -442,13 +478,15 @@ void listFriendsReturnsRosterList() throws Exception { @Test void listFriendsRejectsZeroTenantIdBeforeAccessCheck() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( get("/friends") .param("tenantId", "0") - .param("accountId", "2") + .param("accountId", accountUuid(2L)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) @@ -459,15 +497,17 @@ void listFriendsRejectsZeroTenantIdBeforeAccessCheck() throws Exception { @Test void getFriendRosterSummaryReturnsCanonicalCounts() throws Exception { - when(friendService.getFriendRosterSummary(1L, 2L)) + when(friendService.getFriendRosterSummary(1L, accountUuid(2L))) .thenReturn(new FriendRosterSummaryDto(4, 1, 3, 2, 1, 2, 1, 0, 0, 2, 1, 1)); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( get("/friends/summary") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", accountUuid(2L)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) @@ -487,42 +527,59 @@ void getFriendRosterSummaryReturnsCanonicalCounts() throws Exception { @Test void removeFriendByOrdinalReturnsRemovedEntry() throws Exception { - when(friendService.removeFriendByOrdinal(1L, 2L, 1)) + when(friendService.removeFriendByOrdinal(1L, accountUuid(2L), 1)) .thenReturn( java.util.Optional.of( new FriendRosterEntryDto( 1, 7L, 1L, - 2L, - 3L, + accountUuid(2L), + accountUuid(3L), "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)))); + accountUuid(3L), + false, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null)))); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( delete("/friends/entry/1") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", accountUuid(2L)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.friendAccountId").value(3L)); + .andExpect(jsonPath("$.data.friendAccountId").value(accountUuid(3L))); } @Test void removeFriendByOrdinalRejectsMalformedOrdinalBeforeAccessCheck() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( delete("/friends/entry/not-a-number") .param("tenantId", "1") - .param("accountId", "2") + .param("accountId", accountUuid(2L)) .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 ba64be1d59..2762c4d3f5 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.socialgroups.controller; +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -54,9 +55,9 @@ void clear() { @Test void createGuildAllowsScopedTenantAdmin() throws Exception { - CreateGuildRequest request = new CreateGuildRequest(1L, 2L, "guild"); + CreateGuildRequest request = new CreateGuildRequest(1L, accountUuid(2L), "guild"); when(guildService.createGuild(request)) - .thenReturn(new GuildDto(1L, 1L, "guild", 2L, Instant.now())); + .thenReturn(new GuildDto(1L, 1L, "guild", accountUuid(2L), Instant.now())); String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); mockMvc @@ -72,7 +73,7 @@ void createGuildAllowsScopedTenantAdmin() throws Exception { @Test void createGuildRejectsCrossTenantScopedAdmin() throws Exception { - CreateGuildRequest request = new CreateGuildRequest(1L, 2L, "guild"); + CreateGuildRequest request = new CreateGuildRequest(1L, accountUuid(2L), "guild"); String token = jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); @@ -87,7 +88,7 @@ void createGuildRejectsCrossTenantScopedAdmin() throws Exception { @Test void createGuildRejectsZeroTenantIdBeforeDispatch() throws Exception { - CreateGuildRequest request = new CreateGuildRequest(0L, 2L, "guild"); + CreateGuildRequest request = new CreateGuildRequest(0L, accountUuid(2L), "guild"); String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); mockMvc @@ -106,7 +107,7 @@ void createGuildRejectsZeroTenantIdBeforeDispatch() throws Exception { @Test void addMemberRejectsZeroGuildIdBeforeDispatch() throws Exception { - AddGuildMemberRequest request = new AddGuildMemberRequest(1L, 0L, 2L, "member"); + AddGuildMemberRequest request = new AddGuildMemberRequest(1L, 0L, accountUuid(2L), "member"); String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); mockMvc 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 58c490577c..6c00c2a3c2 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 net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -44,11 +45,16 @@ class MailControllerTest { @Test void sendMailReturnsDto() throws Exception { - SendMailRequest request = new SendMailRequest(1L, 2L, 3L, "hello", "test body"); - MailMessageDto response = new MailMessageDto(1L, 1L, 2L, 3L, "hello", "test body", null, null); + SendMailRequest request = + new SendMailRequest(1L, accountUuid(2L), accountUuid(3L), "hello", "test body"); + MailMessageDto response = + new MailMessageDto( + 1L, 1L, accountUuid(2L), accountUuid(3L), "hello", "test body", null, null); when(mailService.sendMail(request)).thenReturn(response); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( post("/mail") @@ -62,7 +68,9 @@ void sendMailReturnsDto() throws Exception { @Test void sendMailRejectsZeroSenderAccountIdBeforeAccessCheckAndDispatch() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); mockMvc .perform( @@ -71,12 +79,12 @@ void sendMailRejectsZeroSenderAccountIdBeforeAccessCheckAndDispatch() throws Exc .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .content( """ - {"tenantId":1,"senderAccountId":0,"recipientAccountId":3,"subject":"hello","content":"test body"} + {"tenantId":1,"senderAccountId":0,"recipientAccountId":"10000000-0000-4000-8000-000000000003","subject":"hello","content":"test body"} """)) .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("Request body is malformed")); verifyNoInteractions(mailService, socialAccessGuard); } @@ -85,9 +93,9 @@ void sendMailRejectsZeroSenderAccountIdBeforeAccessCheckAndDispatch() throws Exc void sendMailRejectsSenderImpersonationBeforeAccessCheckAndDispatch() throws Exception { String token = jwtUtil.generateToken( - "2", + accountUuid(2L), Map.of( - "accountId", "2", + "accountId", accountUuid(2L), "globalRoles", List.of(), "scopedRoles", Map.of("1", List.of("tenantAdmin")))); @@ -98,7 +106,7 @@ void sendMailRejectsSenderImpersonationBeforeAccessCheckAndDispatch() throws Exc .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .content( """ - {"tenantId":1,"senderAccountId":3,"recipientAccountId":4,"subject":"hello","content":"test body"} + {"tenantId":1,"senderAccountId":"10000000-0000-4000-8000-000000000003","recipientAccountId":"10000000-0000-4000-8000-000000000004","subject":"hello","content":"test body"} """)) .andExpect(status().isForbidden()); 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 5b867a965f..4ba2a87638 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,5 +1,6 @@ package net.firedevops.firemud.socialgroups.controller; +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -45,8 +46,11 @@ class VoiceChatControllerTest { @Test void createTokenReturnsToken() throws Exception { when(service.createToken(any())).thenReturn(new VoiceTokenDto("abc", Instant.now())); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); - String body = "{\"tenantId\":1,\"accountId\":2,\"channelId\":\"guild-1\"}"; + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); + String body = + "{\"tenantId\":1,\"accountId\":\"10000000-0000-4000-8000-000000000002\",\"channelId\":\"guild-1\"}"; mockMvc .perform( @@ -60,7 +64,9 @@ void createTokenReturnsToken() throws Exception { @Test void createTokenRejectsZeroAccountIdBeforeAccessCheckAndDispatch() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2", "globalRoles", List.of())); + String token = + jwtUtil.generateToken( + accountUuid(2L), Map.of("accountId", accountUuid(2L), "globalRoles", List.of())); String body = "{\"tenantId\":1,\"accountId\":0,\"channelId\":\"guild-1\"}"; mockMvc @@ -72,7 +78,7 @@ 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); } diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/dto/SocialAccountUuidRequestTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/dto/SocialAccountUuidRequestTest.java new file mode 100644 index 0000000000..030cad6e55 --- /dev/null +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/dto/SocialAccountUuidRequestTest.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.socialgroups.dto; + +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import net.firedevops.firemud.socialgroups.enums.ChatType; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; + +class SocialAccountUuidRequestTest { + @ParameterizedTest + @NullAndEmptySource + @ValueSource( + strings = { + "42", + "00000000-0000-0000-0000-000000000000", + "1-1-1-1-1", + "10000000-0000-4000-8000-00000000000A", + " 10000000-0000-4000-8000-000000000001" + }) + void everyAccountRequestRejectsNonCanonicalAccountIdentity(String invalid) { + assertThrows( + IllegalArgumentException.class, () -> new AddFriendRequest(7L, invalid, accountUuid(2L))); + assertThrows( + IllegalArgumentException.class, () -> new AddFriendRequest(7L, accountUuid(1L), invalid)); + assertThrows( + IllegalArgumentException.class, () -> new CreateGuildRequest(7L, invalid, "guild")); + assertThrows( + IllegalArgumentException.class, () -> new AddGuildMemberRequest(7L, 9L, invalid, "member")); + assertThrows( + IllegalArgumentException.class, + () -> new UpdateGuildMemberRoleRequest(7L, 9L, invalid, "member")); + assertThrows( + IllegalArgumentException.class, + () -> new SendMailRequest(7L, invalid, accountUuid(2L), "subject", "body")); + assertThrows( + IllegalArgumentException.class, + () -> new SendMailRequest(7L, accountUuid(1L), invalid, "subject", "body")); + assertThrows( + IllegalArgumentException.class, + () -> + new SendMessageRequestDto( + 7L, invalid, ChatType.SAY, "", null, null, null, "body", null)); + assertThrows( + IllegalArgumentException.class, () -> new VoiceTokenRequestDto(7L, invalid, "guild-9")); + assertThrows( + IllegalArgumentException.class, + () -> + new UpdateFriendPresencePolicyRequest( + 7L, invalid, FriendPresenceVisibilityPolicyValue.PRIVATE)); + } + + @Test + void optionalChatRecipientIsAbsentOrCanonicalWhileTenantGuildAndCityKeepTheirOwnIds() { + var request = + new SendMessageRequestDto( + 7L, accountUuid(1L), ChatType.SAY, "", null, 9L, 11L, "body", null); + assertEquals(accountUuid(1L), request.senderAccountId()); + assertNull(request.recipientAccountId()); + assertEquals(7L, request.tenantId()); + assertEquals(9L, request.guildId()); + assertEquals(11L, request.cityId()); + assertThrows( + IllegalArgumentException.class, + () -> + new SendMessageRequestDto( + 7L, accountUuid(1L), ChatType.TELL, "", "2", null, null, "body", null)); + } +} 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 6afa0c3424..de37e761dd 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 @@ -1,5 +1,6 @@ package unit.net.firedevops.firemud.socialgroups.security; +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -9,6 +10,9 @@ import net.firedevops.firemud.socialgroups.security.SocialAccessGuard; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; class SocialAccessGuardTest { private final SocialAccessGuard guard = new SocialAccessGuard(); @@ -18,17 +22,39 @@ void tearDown() { SessionContext.clear(); } - @Test - void hasAccountAccessRejectsMalformedCurrentAccountClaim() { - SessionContext.setContext("not-a-number", List.of(), Map.of()); + @ParameterizedTest + @NullAndEmptySource + @ValueSource( + strings = { + "42", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "10000000-0000-4000-8000-00000000000A", + " 10000000-0000-4000-8000-000000000042" + }) + void hasAccountAccessRejectsMalformedCurrentAccountClaimEvenWithTenantRoles(String claim) { + SessionContext.setContext(claim, List.of("platformAdmin"), Map.of("1", List.of("tenantAdmin"))); + assertFalse(guard.hasAccountAccess(1L, accountUuid(42L))); + } - assertFalse(guard.hasAccountAccess(1L, 42L)); + @Test + void hasAccountAccessAcceptsMatchingCanonicalCurrentAccountClaim() { + SessionContext.setContext(accountUuid(42L), List.of(), Map.of()); + assertTrue(guard.hasAccountAccess(1L, accountUuid(42L))); } @Test - void hasAccountAccessAcceptsMatchingCurrentAccountClaim() { - SessionContext.setContext("42", List.of(), Map.of()); + void hasAccountAccessRejectsAnotherAccountDespiteTenantAndGlobalRoles() { + SessionContext.setContext( + accountUuid(42L), List.of("platformAdmin"), Map.of("1", List.of("tenantAdmin"))); + assertFalse(guard.hasAccountAccess(1L, accountUuid(43L))); + } - assertTrue(guard.hasAccountAccess(1L, 42L)); + @Test + void hasAccountAccessRejectsMalformedRequestedAccountAndAbsentCaller() { + assertFalse(guard.hasAccountAccess(1L, accountUuid(42L))); + SessionContext.setContext(accountUuid(42L), List.of(), Map.of()); + assertFalse(guard.hasAccountAccess(1L, "42")); + assertFalse(guard.hasAccountAccess(0L, accountUuid(42L))); } } 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..23ad67b6b2 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.socialgroups.service.impl; +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -50,7 +51,8 @@ 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(), org.mockito.ArgumentMatchers.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() .setAllowed(true) @@ -80,15 +82,18 @@ void setup() { @Test void sendMessageCachesMessageAndIncrementsMetrics() { SendMessageRequestDto req = - new SendMessageRequestDto(1L, 2L, ChatType.SAY, null, 1L, null, null, "hello", null); + new SendMessageRequestDto( + 1L, accountUuid(2L), ChatType.SAY, null, accountUuid(1L), 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:" + accountUuid(2L), "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:" + accountUuid(2L), + Duration.ofSeconds(props.getSays().historyTtlSeconds())); + verify(listOps).trim("chat:say:1:" + accountUuid(2L), 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, accountUuid(2L), ChatType.SAY, null, accountUuid(1L), null, null, "hello", null); ChatMessageDto dto = service.sendMessage(req); @@ -112,10 +118,12 @@ void sendMessageDefersRedisWritesUntilCommit() { synchronization.afterCommit(); } - verify(listOps).leftPush("chat:say:1:2", "hello"); + verify(listOps).leftPush("chat:say:1:" + accountUuid(2L), "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:" + accountUuid(2L), + Duration.ofSeconds(props.getSays().historyTtlSeconds())); + verify(listOps).trim("chat:say:1:" + accountUuid(2L), 0, props.getSays().maxMessages() - 1); } finally { TransactionSynchronizationManager.clearSynchronization(); } @@ -126,7 +134,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, accountUuid(2L), ChatType.SAY, null, accountUuid(1L), null, null, "hi", null); service.sendMessage(req); assertEquals(1.0, meterRegistry.get("chat_redis_errors_total").counter().count(), 0.001); @@ -136,23 +145,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, accountUuid(2L), ChatType.SAY, null, accountUuid(1L), null, null, "badword", null); service.sendMessage(req); - verify(loggingAdminClient).reportChatViolation(1L, 2L, "Filtered profanity"); + verify(loggingAdminClient).reportChatViolation(1L, accountUuid(2L), "Filtered profanity"); } @Test void moderationPolicyDeniesChatBeforePersistence() { - when(moderationPolicyClient.evaluateChatSend(1L, 2L)) + when(moderationPolicyClient.evaluateChatSend(1L, accountUuid(2L))) .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, accountUuid(2L), ChatType.SAY, null, accountUuid(1L), null, null, "hello", null); IllegalStateException ex = assertThrows(IllegalStateException.class, () -> service.sendMessage(req)); @@ -164,13 +175,24 @@ void moderationPolicyDeniesChatBeforePersistence() { @Test void whisperCachesSeparatelyFromTell() { SendMessageRequestDto req = - new SendMessageRequestDto(1L, 2L, ChatType.WHISPER, null, 7L, null, null, "quiet", null); + new SendMessageRequestDto( + 1L, + accountUuid(2L), + ChatType.WHISPER, + null, + accountUuid(7L), + null, + null, + "quiet", + null); service.sendMessage(req); - verify(listOps).leftPush("chat:whisper:1:7", "quiet"); + verify(listOps).leftPush("chat:whisper:1:" + accountUuid(7L), "quiet"); verify(redisTemplate) - .expire("chat:whisper:1:7", Duration.ofSeconds(props.getWhispers().historyTtlSeconds())); + .expire( + "chat:whisper:1:" + accountUuid(7L), + Duration.ofSeconds(props.getWhispers().historyTtlSeconds())); } @Test @@ -178,7 +200,7 @@ void sendMessageReturnsExistingMessageForDuplicateEffectId() { ChatMessage existing = new ChatMessage(); existing.setId(22L); existing.setTenantId(1L); - existing.setSenderAccountId(2L); + existing.setSenderAccountId(accountUuid(2L)); existing.setType(ChatType.SAY); existing.setContent("hello"); existing.setTimestamp(Instant.parse("2026-04-21T00:00:00Z")); @@ -188,7 +210,15 @@ void sendMessageReturnsExistingMessageForDuplicateEffectId() { ChatMessageDto dto = service.sendMessage( new SendMessageRequestDto( - 1L, 2L, ChatType.SAY, null, 1L, null, null, "hello", "fx-comm-1")); + 1L, + accountUuid(2L), + ChatType.SAY, + null, + accountUuid(1L), + 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..4d4b675e73 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.socialgroups.service.impl; +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -46,14 +47,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 +64,9 @@ private static Map friendsOnlyPolicie @Test void addFriendCreatesAccountScopedLink() { - AddFriendRequest request = new AddFriendRequest(11L, 2L, 3L); + AddFriendRequest request = new AddFriendRequest(11L, accountUuid(2L), accountUuid(3L)); when(accountRepository.findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( - 11L, 2L, 3L, "active")) + 11L, accountUuid(2L), accountUuid(3L), "active")) .thenReturn(java.util.Optional.empty()); when(accountRepository.save(any(AccountFriendLink.class))) .thenAnswer( @@ -78,23 +79,23 @@ void addFriendCreatesAccountScopedLink() { FriendLinkDto result = service.addFriend(request); assertEquals(11L, result.tenantId()); - assertEquals(2L, result.accountId()); - assertEquals(3L, result.friendAccountId()); + assertEquals(accountUuid(2L), result.accountId()); + assertEquals(accountUuid(3L), result.friendAccountId()); assertNotNull(result.createdAt()); } @Test void addFriendReusesExistingActiveAccountScopedLink() { - AddFriendRequest request = new AddFriendRequest(11L, 2L, 3L); + AddFriendRequest request = new AddFriendRequest(11L, accountUuid(2L), accountUuid(3L)); AccountFriendLink existing = new AccountFriendLink(); existing.setId(7L); existing.setTenantId(11L); - existing.setAccountId(2L); - existing.setFriendAccountId(3L); + existing.setAccountId(accountUuid(2L)); + existing.setFriendAccountId(accountUuid(3L)); existing.setStatus("active"); existing.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); when(accountRepository.findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( - 11L, 2L, 3L, "active")) + 11L, accountUuid(2L), accountUuid(3L), "active")) .thenReturn(java.util.Optional.of(existing)); FriendLinkDto result = service.addFriend(request); @@ -106,7 +107,7 @@ void addFriendReusesExistingActiveAccountScopedLink() { @Test void addFriendRejectsSelfLink() { - AddFriendRequest request = new AddFriendRequest(11L, 2L, 2L); + AddFriendRequest request = new AddFriendRequest(11L, accountUuid(2L), accountUuid(2L)); IllegalArgumentException error = assertThrows(IllegalArgumentException.class, () -> service.addFriend(request)); @@ -114,7 +115,7 @@ 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.anyString(), Mockito.anyString(), Mockito.anyString()); } @Test @@ -122,14 +123,14 @@ void removeFriendDeletesExistingActiveAccountScopedLink() { AccountFriendLink existing = new AccountFriendLink(); existing.setId(7L); existing.setTenantId(11L); - existing.setAccountId(2L); - existing.setFriendAccountId(3L); + existing.setAccountId(accountUuid(2L)); + existing.setFriendAccountId(accountUuid(3L)); existing.setStatus("active"); when(accountRepository.findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( - 11L, 2L, 3L, "active")) + 11L, accountUuid(2L), accountUuid(3L), "active")) .thenReturn(java.util.Optional.of(existing)); - service.removeFriend(11L, 2L, 3L); + service.removeFriend(11L, accountUuid(2L), accountUuid(3L)); Mockito.verify(accountRepository).delete(existing); } @@ -137,10 +138,10 @@ void removeFriendDeletesExistingActiveAccountScopedLink() { @Test void removeFriendIsIdempotentWhenActiveLinkDoesNotExist() { when(accountRepository.findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( - 11L, 2L, 3L, "active")) + 11L, accountUuid(2L), accountUuid(3L), "active")) .thenReturn(java.util.Optional.empty()); - service.removeFriend(11L, 2L, 3L); + service.removeFriend(11L, accountUuid(2L), accountUuid(3L)); Mockito.verify(accountRepository, Mockito.never()).delete(any(AccountFriendLink.class)); } @@ -149,29 +150,30 @@ void removeFriendIsIdempotentWhenActiveLinkDoesNotExist() { void listFriendsUsesOnlyMutuallyAcceptedLinks() { AccountFriendLink oneSided = new AccountFriendLink(); oneSided.setTenantId(11L); - oneSided.setAccountId(2L); - oneSided.setFriendAccountId(3L); + oneSided.setAccountId(accountUuid(2L)); + oneSided.setFriendAccountId(accountUuid(3L)); oneSided.setStatus("active"); AccountFriendLink mutual = new AccountFriendLink(); mutual.setTenantId(11L); - mutual.setAccountId(2L); - mutual.setFriendAccountId(4L); + mutual.setAccountId(accountUuid(2L)); + mutual.setFriendAccountId(accountUuid(4L)); mutual.setStatus("active"); - when(accountRepository.findByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findByTenantIdAndAccountIdAndStatus(11L, accountUuid(2L), "active")) .thenReturn(List.of(oneSided)); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "active")) .thenReturn(List.of(mutual)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(4L))) + when(gameSessionClient.queryAccountPresence(11L, accountUuid(2L), List.of(accountUuid(4L)))) .thenReturn(QueryAccountPresenceResponse.newBuilder().build()); - var result = service.listFriends(11L, 2L, FriendRosterFilter.ALL); + var result = service.listFriends(11L, accountUuid(2L), FriendRosterFilter.ALL); assertEquals(1, result.totalCount()); - assertEquals(4L, result.friends().getFirst().friendAccountId()); + assertEquals(accountUuid(4L), result.friends().getFirst().friendAccountId()); Mockito.verify(accountRepository) - .findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active"); + .findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, accountUuid(2L), "active"); Mockito.verify(accountRepository, Mockito.never()) - .findByTenantIdAndAccountIdAndStatus(11L, 2L, "active"); + .findByTenantIdAndAccountIdAndStatus(11L, accountUuid(2L), "active"); } @Test @@ -179,33 +181,38 @@ void getFriendRosterSummaryReturnsCanonicalCounts() { AccountFriendLink sora = new AccountFriendLink(); sora.setId(7L); sora.setTenantId(11L); - sora.setAccountId(2L); - sora.setFriendAccountId(3L); + sora.setAccountId(accountUuid(2L)); + sora.setFriendAccountId(accountUuid(3L)); 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(accountUuid(2L)); + nyx.setFriendAccountId(accountUuid(4L)); nyx.setStatus("active"); nyx.setCreatedAt(Instant.parse("2026-04-10T01:02:04Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "active")) .thenReturn(List.of(sora, nyx)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L, 4L))) + when(gameSessionClient.queryAccountPresence( + 11L, accountUuid(2L), List.of(accountUuid(3L), accountUuid(4L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( - AccountPresenceEntry.newBuilder().setAccountId("3").setOnline(true).build()) + AccountPresenceEntry.newBuilder() + .setAccountId(accountUuid(3L)) + .setOnline(true) + .build()) .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("4") + .setAccountId(accountUuid(4L)) .setOnline(false) .setLastSeenAtMs(Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()) .build()) .build()); - FriendRosterSummaryDto result = service.getFriendRosterSummary(11L, 2L); + FriendRosterSummaryDto result = service.getFriendRosterSummary(11L, accountUuid(2L)); assertEquals(2, result.totalCount()); assertEquals(1, result.onlineCount()); @@ -226,28 +233,29 @@ void getFriendByOrdinalReturnsCanonicalRosterEntry() { AccountFriendLink sora = new AccountFriendLink(); sora.setId(7L); sora.setTenantId(11L); - sora.setAccountId(2L); - sora.setFriendAccountId(3L); + sora.setAccountId(accountUuid(2L)); + sora.setFriendAccountId(accountUuid(3L)); sora.setStatus("active"); sora.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "active")) .thenReturn(List.of(sora)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + when(gameSessionClient.queryAccountPresence(11L, accountUuid(2L), List.of(accountUuid(3L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(accountUuid(3L)) .setOnline(true) .setCharacterName("Ben") .build()) .build()); - var result = service.getFriendByOrdinal(11L, 2L, 1); + var result = service.getFriendByOrdinal(11L, accountUuid(2L), 1); assertTrue(result.isPresent()); assertEquals(1, result.orElseThrow().ordinal()); - assertEquals(3L, result.orElseThrow().friendAccountId()); + assertEquals(accountUuid(3L), result.orElseThrow().friendAccountId()); assertEquals("Ben", result.orElseThrow().presence().characterName()); } @@ -256,22 +264,23 @@ void removeFriendByOrdinalRemovesCanonicalRosterEntry() { AccountFriendLink sora = new AccountFriendLink(); sora.setId(7L); sora.setTenantId(11L); - sora.setAccountId(2L); - sora.setFriendAccountId(3L); + sora.setAccountId(accountUuid(2L)); + sora.setFriendAccountId(accountUuid(3L)); sora.setStatus("active"); sora.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "active")) .thenReturn(List.of(sora)); when(accountRepository.findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( - 11L, 2L, 3L, "active")) + 11L, accountUuid(2L), accountUuid(3L), "active")) .thenReturn(java.util.Optional.of(sora)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + when(gameSessionClient.queryAccountPresence(11L, accountUuid(2L), List.of(accountUuid(3L)))) .thenReturn(QueryAccountPresenceResponse.newBuilder().build()); - var result = service.removeFriendByOrdinal(11L, 2L, 1); + var result = service.removeFriendByOrdinal(11L, accountUuid(2L), 1); assertTrue(result.isPresent()); - assertEquals(3L, result.orElseThrow().friendAccountId()); + assertEquals(accountUuid(3L), result.orElseThrow().friendAccountId()); Mockito.verify(accountRepository).delete(sora); } @@ -280,15 +289,17 @@ void listFriendsFallsBackToOfflineDefaultsWhenPresenceClientReturnsNull() { AccountFriendLink sora = new AccountFriendLink(); sora.setId(7L); sora.setTenantId(11L); - sora.setAccountId(2L); - sora.setFriendAccountId(3L); + sora.setAccountId(accountUuid(2L)); + sora.setFriendAccountId(accountUuid(3L)); sora.setStatus("active"); sora.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "active")) .thenReturn(List.of(sora)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))).thenReturn(null); + when(gameSessionClient.queryAccountPresence(11L, accountUuid(2L), List.of(accountUuid(3L)))) + .thenReturn(null); - var result = service.listFriends(11L, 2L, FriendRosterFilter.ALL); + var result = service.listFriends(11L, accountUuid(2L), FriendRosterFilter.ALL); assertEquals(1, result.totalCount()); assertEquals(false, result.friends().getFirst().presence().online()); @@ -301,13 +312,14 @@ void listFriendsRejectsMalformedPresenceAccountId() { AccountFriendLink sora = new AccountFriendLink(); sora.setId(7L); sora.setTenantId(11L); - sora.setAccountId(2L); - sora.setFriendAccountId(3L); + sora.setAccountId(accountUuid(2L)); + sora.setFriendAccountId(accountUuid(3L)); sora.setStatus("active"); sora.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "active")) .thenReturn(List.of(sora)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + when(gameSessionClient.queryAccountPresence(11L, accountUuid(2L), List.of(accountUuid(3L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( @@ -317,10 +329,10 @@ void listFriendsRejectsMalformedPresenceAccountId() { IllegalStateException error = assertThrows( IllegalStateException.class, - () -> service.listFriends(11L, 2L, FriendRosterFilter.ALL)); + () -> service.listFriends(11L, accountUuid(2L), 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 +340,14 @@ void listFriendPresenceRejectsMalformedPresenceAccountId() { AccountFriendLink sora = new AccountFriendLink(); sora.setId(7L); sora.setTenantId(11L); - sora.setAccountId(2L); - sora.setFriendAccountId(3L); + sora.setAccountId(accountUuid(2L)); + sora.setFriendAccountId(accountUuid(3L)); sora.setStatus("active"); sora.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "active")) .thenReturn(List.of(sora)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + when(gameSessionClient.queryAccountPresence(11L, accountUuid(2L), List.of(accountUuid(3L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( @@ -342,20 +355,21 @@ void listFriendPresenceRejectsMalformedPresenceAccountId() { .build()); IllegalStateException error = - assertThrows(IllegalStateException.class, () -> service.listFriendPresence(11L, 2L)); + assertThrows( + IllegalStateException.class, () -> service.listFriendPresence(11L, accountUuid(2L))); 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, accountUuid(2L), List.of(accountUuid(3L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(accountUuid(3L)) .setOnline(true) .setGameInstanceId("0") .setCharacterId("-7") @@ -364,37 +378,38 @@ void listFriendPresenceDropsNonPositiveVisibleIds() { AccountFriendLink sora = new AccountFriendLink(); sora.setId(7L); sora.setTenantId(11L); - sora.setAccountId(2L); - sora.setFriendAccountId(3L); + sora.setAccountId(accountUuid(2L)); + sora.setFriendAccountId(accountUuid(3L)); sora.setStatus("active"); sora.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "active")) .thenReturn(List.of(sora)); - var result = service.listFriendPresence(11L, 2L, FriendRosterFilter.ALL); + var result = service.listFriendPresence(11L, accountUuid(2L), FriendRosterFilter.ALL); assertEquals(1, result.presences().size()); - assertEquals(3L, result.presences().getFirst().friendAccountId()); + assertEquals(accountUuid(3L), 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, accountUuid(2L))) .thenReturn(Optional.of(FriendPresenceVisibilityPolicyValue.PRIVATE)); - var result = service.getFriendPresencePolicy(11L, 2L); + var result = service.getFriendPresencePolicy(11L, accountUuid(2L)); assertEquals(FriendPresenceVisibilityPolicyValue.PRIVATE, result.currentPolicy()); } @Test void getFriendPresencePolicyRedactsLegacyHiddenStaff() { - when(accountClient.getPresenceVisibilityPolicy(11L, 2L)) + when(accountClient.getPresenceVisibilityPolicy(11L, accountUuid(2L))) .thenReturn(Optional.of(FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF)); - var result = service.getFriendPresencePolicy(11L, 2L); + var result = service.getFriendPresencePolicy(11L, accountUuid(2L)); assertEquals(FriendPresenceVisibilityPolicyValue.PRIVATE, result.currentPolicy()); } @@ -406,7 +421,7 @@ void updateFriendPresencePolicyRejectsHiddenStaff() { IllegalArgumentException.class, () -> service.updateFriendPresencePolicy( - 11L, 2L, FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF)); + 11L, accountUuid(2L), FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF)); assertEquals("Friend presence visibility policy HIDDEN_STAFF is reserved", error.getMessage()); } @@ -414,11 +429,12 @@ void updateFriendPresencePolicyRejectsHiddenStaff() { @Test void updateFriendPresencePolicyWritesCanonicalAccountPolicy() { when(accountClient.updatePresenceVisibilityPolicy( - 11L, 2L, FriendPresenceVisibilityPolicyValue.PUBLIC)) + 11L, accountUuid(2L), FriendPresenceVisibilityPolicyValue.PUBLIC)) .thenReturn(true); var result = - service.updateFriendPresencePolicy(11L, 2L, FriendPresenceVisibilityPolicyValue.PUBLIC); + service.updateFriendPresencePolicy( + 11L, accountUuid(2L), FriendPresenceVisibilityPolicyValue.PUBLIC); assertEquals(FriendPresenceVisibilityPolicyValue.PUBLIC, result.currentPolicy()); } @@ -426,12 +442,14 @@ void updateFriendPresencePolicyWritesCanonicalAccountPolicy() { @Test void removeFriendRejectsSelfLink() { IllegalArgumentException error = - assertThrows(IllegalArgumentException.class, () -> service.removeFriend(11L, 2L, 2L)); + assertThrows( + IllegalArgumentException.class, + () -> service.removeFriend(11L, accountUuid(2L), accountUuid(2L))); 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.anyString(), Mockito.anyString(), Mockito.anyString()); } @Test @@ -439,18 +457,19 @@ void getFriendReturnsCanonicalRosterEntryWithEmbeddedPresence() { AccountFriendLink link = new AccountFriendLink(); link.setId(7L); link.setTenantId(11L); - link.setAccountId(2L); - link.setFriendAccountId(3L); + link.setAccountId(accountUuid(2L)); + link.setFriendAccountId(accountUuid(3L)); link.setStatus("active"); link.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "active")) .thenReturn(List.of(link)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + when(gameSessionClient.queryAccountPresence(11L, accountUuid(2L), List.of(accountUuid(3L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(accountUuid(3L)) .setOnline(true) .setGameInstanceId("9") .setPlayableStateScope( @@ -466,11 +485,11 @@ void getFriendReturnsCanonicalRosterEntryWithEmbeddedPresence() { .build()) .build()); - var result = service.getFriend(11L, 2L, 3L); + var result = service.getFriend(11L, accountUuid(2L), accountUuid(3L)); assertTrue(result.isPresent()); assertEquals(7L, result.orElseThrow().friendLinkId()); - assertEquals(3L, result.orElseThrow().friendAccountId()); + assertEquals(accountUuid(3L), result.orElseThrow().friendAccountId()); assertEquals(true, result.orElseThrow().presence().online()); assertEquals("Ben", result.orElseThrow().presence().characterName()); } @@ -479,19 +498,20 @@ void getFriendReturnsCanonicalRosterEntryWithEmbeddedPresence() { void listFriendPresenceReturnsOrderedSnapshotsFromGameSession() { AccountFriendLink link = new AccountFriendLink(); link.setTenantId(11L); - link.setAccountId(2L); - link.setFriendAccountId(3L); + link.setAccountId(accountUuid(2L)); + link.setFriendAccountId(accountUuid(3L)); link.setStatus("active"); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "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(accountUuid(3L)))) + .thenReturn(Map.of(accountUuid(3L), FriendPresenceVisibilityPolicyValue.PUBLIC)); + when(gameSessionClient.queryAccountPresence(11L, accountUuid(2L), List.of(accountUuid(3L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(accountUuid(3L)) .setOnline(true) .setGameInstanceId("9") .setWorldSlug("demo") @@ -510,13 +530,13 @@ void listFriendPresenceReturnsOrderedSnapshotsFromGameSession() { .build()) .build()); - var result = service.listFriendPresence(11L, 2L); + var result = service.listFriendPresence(11L, accountUuid(2L)); 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(accountUuid(3L), 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 +553,19 @@ void listFriendsReturnsRosterEntriesWithEmbeddedPresence() { AccountFriendLink link = new AccountFriendLink(); link.setId(7L); link.setTenantId(11L); - link.setAccountId(2L); - link.setFriendAccountId(3L); + link.setAccountId(accountUuid(2L)); + link.setFriendAccountId(accountUuid(3L)); link.setStatus("active"); link.setCreatedAt(Instant.parse("2026-04-10T01:02:03Z")); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "active")) .thenReturn(List.of(link)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + when(gameSessionClient.queryAccountPresence(11L, accountUuid(2L), List.of(accountUuid(3L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(accountUuid(3L)) .setOnline(true) .setGameInstanceId("9") .setPlayableStateScope( @@ -566,15 +587,15 @@ void listFriendsReturnsRosterEntriesWithEmbeddedPresence() { .build()) .build()); - var result = service.listFriends(11L, 2L, FriendRosterFilter.ALL); + var result = service.listFriends(11L, accountUuid(2L), 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(accountUuid(2L), result.friends().get(0).accountId()); + assertEquals(accountUuid(3L), 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 +609,42 @@ void listFriendsFiltersOnlineWithoutRenumberingCanonicalOrdinals() { AccountFriendLink onlineLink = new AccountFriendLink(); onlineLink.setId(7L); onlineLink.setTenantId(11L); - onlineLink.setAccountId(2L); - onlineLink.setFriendAccountId(3L); + onlineLink.setAccountId(accountUuid(2L)); + onlineLink.setFriendAccountId(accountUuid(3L)); onlineLink.setStatus("active"); AccountFriendLink offlineLink = new AccountFriendLink(); offlineLink.setId(8L); offlineLink.setTenantId(11L); - offlineLink.setAccountId(2L); - offlineLink.setFriendAccountId(4L); + offlineLink.setAccountId(accountUuid(2L)); + offlineLink.setFriendAccountId(accountUuid(4L)); offlineLink.setStatus("active"); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "active")) .thenReturn(List.of(onlineLink, offlineLink)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L, 4L))) + when(gameSessionClient.queryAccountPresence( + 11L, accountUuid(2L), List.of(accountUuid(3L), accountUuid(4L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( - AccountPresenceEntry.newBuilder().setAccountId("3").setOnline(true).build()) + AccountPresenceEntry.newBuilder() + .setAccountId(accountUuid(3L)) + .setOnline(true) + .build()) .addPresences( - AccountPresenceEntry.newBuilder().setAccountId("4").setOnline(false).build()) + AccountPresenceEntry.newBuilder() + .setAccountId(accountUuid(4L)) + .setOnline(false) + .build()) .build()); - var result = service.listFriends(11L, 2L, FriendRosterFilter.ONLINE); + var result = service.listFriends(11L, accountUuid(2L), 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(accountUuid(3L), result.friends().get(0).friendAccountId()); } @Test @@ -623,39 +652,45 @@ void listFriendsFiltersVisibilityPolicyWithoutRenumberingCanonicalOrdinals() { AccountFriendLink friendsOnlyLink = new AccountFriendLink(); friendsOnlyLink.setId(7L); friendsOnlyLink.setTenantId(11L); - friendsOnlyLink.setAccountId(2L); - friendsOnlyLink.setFriendAccountId(3L); + friendsOnlyLink.setAccountId(accountUuid(2L)); + friendsOnlyLink.setFriendAccountId(accountUuid(3L)); friendsOnlyLink.setStatus("active"); AccountFriendLink privateLink = new AccountFriendLink(); privateLink.setId(8L); privateLink.setTenantId(11L); - privateLink.setAccountId(2L); - privateLink.setFriendAccountId(4L); + privateLink.setAccountId(accountUuid(2L)); + privateLink.setFriendAccountId(accountUuid(4L)); privateLink.setStatus("active"); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "active")) .thenReturn(List.of(friendsOnlyLink, privateLink)); - when(accountClient.getPresenceVisibilityPolicies(11L, List.of(3L, 4L))) + when(accountClient.getPresenceVisibilityPolicies( + 11L, List.of(accountUuid(3L), accountUuid(4L)))) .thenReturn( Map.of( - 3L, FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY, - 4L, FriendPresenceVisibilityPolicyValue.PRIVATE)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L))) + accountUuid(3L), FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY, + accountUuid(4L), FriendPresenceVisibilityPolicyValue.PRIVATE)); + when(gameSessionClient.queryAccountPresence(11L, accountUuid(2L), List.of(accountUuid(3L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( - AccountPresenceEntry.newBuilder().setAccountId("3").setOnline(true).build()) + AccountPresenceEntry.newBuilder() + .setAccountId(accountUuid(3L)) + .setOnline(true) + .build()) .build()); - var result = service.listFriends(11L, 2L, FriendRosterFilter.FRIENDS_ONLY); + var result = service.listFriends(11L, accountUuid(2L), 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(accountUuid(3L), 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, accountUuid(2L), List.of(accountUuid(3L))); } @Test @@ -663,23 +698,25 @@ void listFriendsFiltersPlayableStateScopeWithoutRenumberingCanonicalOrdinals() { AccountFriendLink sharedLink = new AccountFriendLink(); sharedLink.setId(7L); sharedLink.setTenantId(11L); - sharedLink.setAccountId(2L); - sharedLink.setFriendAccountId(3L); + sharedLink.setAccountId(accountUuid(2L)); + sharedLink.setFriendAccountId(accountUuid(3L)); sharedLink.setStatus("active"); AccountFriendLink isolatedLink = new AccountFriendLink(); isolatedLink.setId(8L); isolatedLink.setTenantId(11L); - isolatedLink.setAccountId(2L); - isolatedLink.setFriendAccountId(4L); + isolatedLink.setAccountId(accountUuid(2L)); + isolatedLink.setFriendAccountId(accountUuid(4L)); isolatedLink.setStatus("active"); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "active")) .thenReturn(List.of(sharedLink, isolatedLink)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L, 4L))) + when(gameSessionClient.queryAccountPresence( + 11L, accountUuid(2L), List.of(accountUuid(3L), accountUuid(4L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(accountUuid(3L)) .setOnline(true) .setPlayableStateScope( net.firedevops.firemud.entitymanagement.v1.PlayableStateScope @@ -687,7 +724,7 @@ void listFriendsFiltersPlayableStateScopeWithoutRenumberingCanonicalOrdinals() { .build()) .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("4") + .setAccountId(accountUuid(4L)) .setOnline(true) .setPlayableStateScope( net.firedevops.firemud.entitymanagement.v1.PlayableStateScope @@ -695,14 +732,14 @@ void listFriendsFiltersPlayableStateScopeWithoutRenumberingCanonicalOrdinals() { .build()) .build()); - var result = service.listFriends(11L, 2L, FriendRosterFilter.SHARED); + var result = service.listFriends(11L, accountUuid(2L), 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(accountUuid(3L), result.friends().get(0).friendAccountId()); assertEquals("SHARED", result.friends().get(0).presence().playableStateScope()); } @@ -710,27 +747,30 @@ void listFriendsFiltersPlayableStateScopeWithoutRenumberingCanonicalOrdinals() { void listFriendPresenceRedactsLegacyHiddenStaffAsPrivate() { AccountFriendLink privateLink = new AccountFriendLink(); privateLink.setTenantId(11L); - privateLink.setAccountId(2L); - privateLink.setFriendAccountId(3L); + privateLink.setAccountId(accountUuid(2L)); + privateLink.setFriendAccountId(accountUuid(3L)); privateLink.setStatus("active"); AccountFriendLink hiddenLink = new AccountFriendLink(); hiddenLink.setTenantId(11L); - hiddenLink.setAccountId(2L); - hiddenLink.setFriendAccountId(4L); + hiddenLink.setAccountId(accountUuid(2L)); + hiddenLink.setFriendAccountId(accountUuid(4L)); hiddenLink.setStatus("active"); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "active")) .thenReturn(List.of(privateLink, hiddenLink)); - when(accountClient.getPresenceVisibilityPolicies(11L, List.of(3L, 4L))) + when(accountClient.getPresenceVisibilityPolicies( + 11L, List.of(accountUuid(3L), accountUuid(4L)))) .thenReturn( Map.of( - 3L, FriendPresenceVisibilityPolicyValue.PRIVATE, - 4L, FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF)); - when(gameSessionClient.queryAccountPresence(11L, 2L, List.of(3L, 4L))) + accountUuid(3L), FriendPresenceVisibilityPolicyValue.PRIVATE, + accountUuid(4L), FriendPresenceVisibilityPolicyValue.HIDDEN_STAFF)); + when(gameSessionClient.queryAccountPresence( + 11L, accountUuid(2L), List.of(accountUuid(3L), accountUuid(4L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(accountUuid(3L)) .setOnline(true) .setGameInstanceId("9") .setWorldSlug("demo") @@ -746,7 +786,7 @@ void listFriendPresenceRedactsLegacyHiddenStaffAsPrivate() { .build()) .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("4") + .setAccountId(accountUuid(4L)) .setOnline(true) .setGameInstanceId("10") .setCharacterId("100") @@ -757,7 +797,7 @@ void listFriendPresenceRedactsLegacyHiddenStaffAsPrivate() { .build()) .build()); - var result = service.listFriendPresence(11L, 2L); + var result = service.listFriendPresence(11L, accountUuid(2L)); assertEquals(2, result.totalCount()); assertEquals(2, result.matchCount()); @@ -790,17 +830,18 @@ 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, accountUuid(2L), FriendRosterFilter.PRIVATE); assertEquals(2, privateFiltered.totalCount()); assertEquals(2, privateFiltered.matchCount()); assertEquals(1, privateFiltered.friends().getFirst().ordinal()); - assertEquals(3L, privateFiltered.friends().getFirst().friendAccountId()); + assertEquals(accountUuid(3L), 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(accountUuid(4L), 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, accountUuid(2L), FriendRosterFilter.HIDDEN_STAFF); assertEquals(FriendRosterFilter.PRIVATE, hiddenStaffFiltered.filter()); assertEquals(2, hiddenStaffFiltered.totalCount()); assertEquals(2, hiddenStaffFiltered.matchCount()); @@ -809,9 +850,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, accountUuid(2L)); assertEquals(2, summary.totalCount()); assertEquals(0, summary.onlineCount()); assertEquals(2, summary.offlineCount()); @@ -828,18 +869,20 @@ void listFriendPresenceRedactsLegacyHiddenStaffAsPrivate() { void listFriendPresenceFailsClosedWhenAccountPolicyBatchIsUnavailable() { AccountFriendLink link = new AccountFriendLink(); link.setTenantId(11L); - link.setAccountId(2L); - link.setFriendAccountId(3L); + link.setAccountId(accountUuid(2L)); + link.setFriendAccountId(accountUuid(3L)); link.setStatus("active"); - when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus(11L, 2L, "active")) + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "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(accountUuid(3L)))) + .thenReturn(null); + when(gameSessionClient.queryAccountPresence(11L, accountUuid(2L), List.of(accountUuid(3L)))) .thenReturn( QueryAccountPresenceResponse.newBuilder() .addPresences( AccountPresenceEntry.newBuilder() - .setAccountId("3") + .setAccountId(accountUuid(3L)) .setOnline(true) .setGameInstanceId("9") .setPlayableStateScope( @@ -861,11 +904,11 @@ void listFriendPresenceFailsClosedWhenAccountPolicyBatchIsUnavailable() { .build()) .build()); - var result = service.listFriendPresence(11L, 2L); + var result = service.listFriendPresence(11L, accountUuid(2L)); assertEquals(1, result.totalCount()); assertEquals(1, result.matchCount()); - assertEquals(3L, result.presences().get(0).friendAccountId()); + assertEquals(accountUuid(3L), 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,15 +924,45 @@ 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, accountUuid(2L), FriendRosterFilter.PRIVATE); assertEquals(1, privateFiltered.matchCount()); - assertEquals(3L, privateFiltered.friends().getFirst().friendAccountId()); + assertEquals(accountUuid(3L), privateFiltered.friends().getFirst().friendAccountId()); assertNull(privateFiltered.friends().getFirst().presence().visibilityPolicy()); - var summary = service.getFriendRosterSummary(11L, 2L); + var summary = service.getFriendRosterSummary(11L, accountUuid(2L)); assertEquals(1, summary.privateCount()); assertEquals(0, summary.unspecifiedVisibilityCount()); } + + @Test + void rawPresenceCannotSubstituteAnotherCanonicalAccountOrRepeatASubject() { + AccountFriendLink link = new AccountFriendLink(); + link.setTenantId(11L); + link.setAccountId(accountUuid(2L)); + link.setFriendAccountId(accountUuid(3L)); + link.setStatus("active"); + when(accountRepository.findMutuallyAcceptedByTenantIdAndAccountIdAndStatus( + 11L, accountUuid(2L), "active")) + .thenReturn(List.of(link)); + when(gameSessionClient.queryAccountPresence(11L, accountUuid(2L), List.of(accountUuid(3L)))) + .thenReturn( + QueryAccountPresenceResponse.newBuilder() + .addPresences( + AccountPresenceEntry.newBuilder() + .setAccountId(accountUuid(99L)) + .setOnline(true)) + .build()); + assertThrows(IllegalStateException.class, () -> service.listFriends(11L, accountUuid(2L))); + var entry = + AccountPresenceEntry.newBuilder().setAccountId(accountUuid(3L)).setOnline(true).build(); + when(gameSessionClient.queryAccountPresence(11L, accountUuid(2L), List.of(accountUuid(3L)))) + .thenReturn( + QueryAccountPresenceResponse.newBuilder() + .addPresences(entry) + .addPresences(entry) + .build()); + assertThrows(IllegalStateException.class, () -> service.listFriends(11L, accountUuid(2L))); + } } 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..26965977b5 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.socialgroups.service.impl; +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; @@ -41,19 +42,19 @@ void setUp() { @Test void addMemberReturnsDto() throws Exception { - AddGuildMemberRequest request = new AddGuildMemberRequest(1L, 2L, 3L, "member"); + AddGuildMemberRequest request = new AddGuildMemberRequest(1L, 2L, accountUuid(3L), "member"); GuildMember saved = new GuildMember(); saved.setId(1L); saved.setTenantId(1L); saved.setGuildId(2L); - saved.setAccountId(3L); + saved.setAccountId(accountUuid(3L)); saved.setRole("member"); when(repository.save(any(GuildMember.class))).thenReturn(saved); GuildMemberDto dto = service.addMember(request); - assertEquals(3L, dto.accountId()); + assertEquals(accountUuid(3L), dto.accountId()); assertEquals("member", dto.role()); - verify(loggingAdminClient).reportChatViolation(1L, 3L, "Joined guild 2"); + verify(loggingAdminClient).reportChatViolation(1L, accountUuid(3L), "Joined guild 2"); } @Test @@ -62,17 +63,19 @@ void updateMemberRoleUsesRepositoryLookup() throws Exception { member.setId(5L); member.setTenantId(1L); member.setGuildId(2L); - member.setAccountId(3L); + member.setAccountId(accountUuid(3L)); member.setRole("member"); - when(repository.findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, 3L)) + when(repository.findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, accountUuid(3L))) .thenReturn(java.util.Optional.of(member)); GuildMemberDto dto = - service.updateMemberRole(new UpdateGuildMemberRoleRequest(1L, 2L, 3L, "officer")); + service.updateMemberRole( + new UpdateGuildMemberRoleRequest(1L, 2L, accountUuid(3L), "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, accountUuid(3L)); + verify(loggingAdminClient) + .reportChatViolation(1L, accountUuid(3L), "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(accountUuid(3L)); member.setRole("member"); - when(repository.findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, 3L)) + when(repository.findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, accountUuid(3L))) .thenReturn(java.util.Optional.of(member)); - service.removeMember(1L, 2L, 3L); + service.removeMember(1L, 2L, accountUuid(3L)); - verify(repository).findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, 3L); + verify(repository).findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, accountUuid(3L)); verify(repository).delete(member); - verify(loggingAdminClient).reportChatViolation(1L, 3L, "Left guild 2"); + verify(loggingAdminClient).reportChatViolation(1L, accountUuid(3L), "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..c8aed94392 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.socialgroups.service.impl; +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @@ -28,12 +29,13 @@ void setUp() { @Test void sendMailReturnsDto() { - SendMailRequest request = new SendMailRequest(1L, 2L, 3L, "hello", "body"); + SendMailRequest request = + new SendMailRequest(1L, accountUuid(2L), accountUuid(3L), "hello", "body"); MailMessage saved = new MailMessage(); saved.setId(1L); saved.setTenantId(1L); - saved.setSenderAccountId(2L); - saved.setRecipientAccountId(3L); + saved.setSenderAccountId(accountUuid(2L)); + saved.setRecipientAccountId(accountUuid(3L)); saved.setSubject("hello"); saved.setContent("body"); saved.setSentAt(Instant.now()); @@ -41,6 +43,6 @@ void sendMailReturnsDto() { MailMessageDto result = service.sendMail(request); assertEquals("hello", result.subject()); - assertEquals(3L, result.recipientAccountId()); + assertEquals(accountUuid(3L), 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..e7a35f4ffd 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.socialgroups.service.impl; +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.verify; @@ -84,7 +85,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, accountUuid(2L))).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -93,7 +94,7 @@ void createGuildErrorReturnsErrorDetail() { service.createGuild( net.firedevops.firemud.socialgroups.v1.CreateGuildRequest.newBuilder() .setTenantId("1") - .setOwnerAccountId("2") + .setOwnerAccountId(accountUuid(2L)) .setName("test") .build(), new StreamObserver<>() { @@ -122,7 +123,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, accountUuid(2L))).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -131,7 +132,7 @@ void createGuildRuntimeFailureReturnsInternalErrorDetail() { service.createGuild( net.firedevops.firemud.socialgroups.v1.CreateGuildRequest.newBuilder() .setTenantId("1") - .setOwnerAccountId("2") + .setOwnerAccountId(accountUuid(2L)) .setName("test") .build(), new StreamObserver<>() { @@ -159,7 +160,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, accountUuid(2L))).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -168,9 +169,9 @@ void sendMessageMapsWhisperProtoToDomainEnum() { service.sendMessage( net.firedevops.firemud.socialgroups.v1.SendMessageRequest.newBuilder() .setTenantId("1") - .setSenderId("2") + .setSenderId(accountUuid(2L)) .setType(net.firedevops.firemud.socialgroups.v1.ChatType.CHAT_TYPE_WHISPER) - .setRecipientId("7") + .setRecipientId(accountUuid(7L)) .setContent("quiet") .build(), new StreamObserver<>() { @@ -188,7 +189,16 @@ public void onCompleted() {} verify(chat) .sendMessage( - new SendMessageRequestDto(1L, 2L, ChatType.WHISPER, "", 7L, null, null, "quiet", null)); + new SendMessageRequestDto( + 1L, + accountUuid(2L), + ChatType.WHISPER, + "", + accountUuid(7L), + null, + null, + "quiet", + null)); assertNotNull(ref.get()); assertEquals(true, ref.get().getSuccess()); } @@ -201,7 +211,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, accountUuid(2L))).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -209,7 +219,7 @@ void sendMessageMapsEffectIdToDomainRequest() { service.sendMessage( net.firedevops.firemud.socialgroups.v1.SendMessageRequest.newBuilder() .setTenantId("1") - .setSenderId("2") + .setSenderId(accountUuid(2L)) .setType(net.firedevops.firemud.socialgroups.v1.ChatType.CHAT_TYPE_SAY) .setContent("hello") .setEffectId("fx-comm-2") @@ -228,7 +238,7 @@ public void onCompleted() {} verify(chat) .sendMessage( new SendMessageRequestDto( - 1L, 2L, ChatType.SAY, "", null, null, null, "hello", "fx-comm-2")); + 1L, accountUuid(2L), ChatType.SAY, "", null, null, null, "hello", "fx-comm-2")); } @Test @@ -239,7 +249,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, accountUuid(2L))).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -248,7 +258,7 @@ void sendMessageRejectsZeroRecipientIdBeforeDispatch() { service.sendMessage( net.firedevops.firemud.socialgroups.v1.SendMessageRequest.newBuilder() .setTenantId("1") - .setSenderId("2") + .setSenderId(accountUuid(2L)) .setType(net.firedevops.firemud.socialgroups.v1.ChatType.CHAT_TYPE_TELL) .setRecipientId("0") .setContent("hello") @@ -281,7 +291,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, accountUuid(2L))).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -290,7 +300,7 @@ void sendMessageTreatsBlankOptionalIdsAsAbsent() { service.sendMessage( net.firedevops.firemud.socialgroups.v1.SendMessageRequest.newBuilder() .setTenantId("1") - .setSenderId("2") + .setSenderId(accountUuid(2L)) .setType(net.firedevops.firemud.socialgroups.v1.ChatType.CHAT_TYPE_SAY) .setRecipientId(" ") .setGuildId(" ") @@ -312,7 +322,8 @@ public void onCompleted() {} verify(chat) .sendMessage( - new SendMessageRequestDto(1L, 2L, ChatType.SAY, "", null, null, null, "hello", null)); + new SendMessageRequestDto( + 1L, accountUuid(2L), ChatType.SAY, "", null, null, null, "hello", null)); assertNotNull(ref.get()); assertEquals(true, ref.get().getSuccess()); } @@ -325,8 +336,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, accountUuid(2L))).thenReturn(true); + Mockito.when(friend.listFriendPresence(1L, accountUuid(2L), FriendRosterFilter.FRIENDS_ONLY)) .thenReturn( new net.firedevops.firemud.socialgroups.dto.FriendPresenceViewDto( FriendRosterFilter.FRIENDS_ONLY, @@ -334,7 +345,7 @@ void listFriendPresenceMapsDtosToProtoEntries() { 1, List.of( new FriendPresenceDto( - 3L, + accountUuid(3L), true, 9L, "demo", @@ -354,7 +365,7 @@ void listFriendPresenceMapsDtosToProtoEntries() { service.listFriendPresence( net.firedevops.firemud.socialgroups.v1.ListFriendPresenceRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(accountUuid(2L)) .setFilter( net.firedevops.firemud.socialgroups.v1.FriendRosterFilter .FRIEND_ROSTER_FILTER_FRIENDS_ONLY) @@ -374,7 +385,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals(1, ref.get().getPresencesCount()); - assertEquals("3", ref.get().getPresences(0).getFriendAccountId()); + assertEquals(accountUuid(3L), 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 +413,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, accountUuid(2L))).thenReturn(true); + Mockito.when(friend.getFriend(1L, accountUuid(2L), accountUuid(3L))) .thenReturn( java.util.Optional.of( new FriendRosterEntryDto( 1, 7L, 1L, - 2L, - 3L, + accountUuid(2L), + accountUuid(3L), "active", Instant.parse("2026-04-10T01:02:03Z"), new FriendPresenceDto( - 3L, + accountUuid(3L), true, 9L, "SHARED", @@ -438,8 +449,8 @@ void getFriendMapsRosterDtoToProtoEntry() { service.getFriend( net.firedevops.firemud.socialgroups.v1.GetFriendRequest.newBuilder() .setTenantId("1") - .setAccountId("2") - .setFriendAccountId("3") + .setAccountId(accountUuid(2L)) + .setFriendAccountId(accountUuid(3L)) .build(), new StreamObserver<>() { @Override @@ -455,7 +466,7 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("3", ref.get().getFriend().getFriendAccountId()); + assertEquals(accountUuid(3L), ref.get().getFriend().getFriendAccountId()); assertEquals("7", ref.get().getFriend().getFriendLinkId()); assertEquals("Ben", ref.get().getFriend().getPresence().getCharacterName()); } @@ -468,7 +479,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, accountUuid(2L))).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -477,8 +488,8 @@ void removeFriendInvokesServiceAndReturnsSuccess() { service.removeFriend( net.firedevops.firemud.socialgroups.v1.RemoveFriendRequest.newBuilder() .setTenantId("1") - .setAccountId("2") - .setFriendAccountId("3") + .setAccountId(accountUuid(2L)) + .setFriendAccountId(accountUuid(3L)) .build(), new StreamObserver<>() { @Override @@ -493,7 +504,7 @@ public void onError(Throwable t) {} public void onCompleted() {} }); - verify(friend).removeFriend(1L, 2L, 3L); + verify(friend).removeFriend(1L, accountUuid(2L), accountUuid(3L)); assertNotNull(ref.get()); assertEquals(true, ref.get().getSuccess()); } @@ -509,7 +520,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, accountUuid(2L))).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -519,8 +530,8 @@ void addFriendIllegalArgumentReturnsErrorDetail() { service.addFriend( net.firedevops.firemud.socialgroups.v1.AddFriendRequest.newBuilder() .setTenantId("1") - .setAccountId("2") - .setFriendAccountId("2") + .setAccountId(accountUuid(2L)) + .setFriendAccountId(accountUuid(2L)) .build(), new StreamObserver<>() { @Override @@ -550,10 +561,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, accountUuid(2L), accountUuid(2L)); 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, accountUuid(2L))).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -562,8 +573,8 @@ void removeFriendIllegalArgumentReturnsErrorDetail() { service.removeFriend( net.firedevops.firemud.socialgroups.v1.RemoveFriendRequest.newBuilder() .setTenantId("1") - .setAccountId("2") - .setFriendAccountId("2") + .setAccountId(accountUuid(2L)) + .setFriendAccountId(accountUuid(2L)) .build(), new StreamObserver<>() { @Override @@ -592,8 +603,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, accountUuid(2L))).thenReturn(true); + Mockito.when(friend.listFriends(1L, accountUuid(2L), FriendRosterFilter.FRIENDS_ONLY)) .thenReturn( new FriendRosterViewDto( FriendRosterFilter.FRIENDS_ONLY, @@ -604,12 +615,12 @@ void listFriendsMapsDtosToProtoEntries() { 1, 7L, 1L, - 2L, - 3L, + accountUuid(2L), + accountUuid(3L), "active", Instant.parse("2026-04-10T01:02:03Z"), new FriendPresenceDto( - 3L, + accountUuid(3L), true, 9L, "SHARED", @@ -631,7 +642,7 @@ void listFriendsMapsDtosToProtoEntries() { service.listFriends( net.firedevops.firemud.socialgroups.v1.ListFriendsRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(accountUuid(2L)) .setFilter( net.firedevops.firemud.socialgroups.v1.FriendRosterFilter .FRIEND_ROSTER_FILTER_FRIENDS_ONLY) @@ -658,7 +669,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(accountUuid(3L), ref.get().getFriends(0).getFriendAccountId()); assertEquals("active", ref.get().getFriends(0).getStatus()); assertEquals( Instant.parse("2026-04-10T01:02:03Z").toEpochMilli(), @@ -679,8 +690,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, accountUuid(2L))).thenReturn(true); + Mockito.when(friend.getFriendRosterSummary(1L, accountUuid(2L))) .thenReturn(new FriendRosterSummaryDto(4, 1, 3, 2, 1, 2, 1, 0, 0, 2, 1, 1)); SocialGroupsGrpcService service = new SocialGroupsGrpcService( @@ -690,7 +701,7 @@ void getFriendRosterSummaryMapsCanonicalCounts() { service.getFriendRosterSummary( net.firedevops.firemud.socialgroups.v1.GetFriendRosterSummaryRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(accountUuid(2L)) .build(), new StreamObserver<>() { @Override @@ -728,21 +739,34 @@ 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, accountUuid(2L))).thenReturn(true); + Mockito.when(friend.getFriendByOrdinal(1L, accountUuid(2L), 1)) .thenReturn( java.util.Optional.of( new FriendRosterEntryDto( 1, 7L, 1L, - 2L, - 3L, + accountUuid(2L), + accountUuid(3L), "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)))); + accountUuid(3L), + 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 +775,7 @@ void getFriendByOrdinalMapsCanonicalEntry() { service.getFriendByOrdinal( net.firedevops.firemud.socialgroups.v1.GetFriendByOrdinalRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(accountUuid(2L)) .setOrdinal(1) .build(), new StreamObserver<>() { @@ -769,7 +793,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals(1, ref.get().getFriend().getOrdinal()); - assertEquals("3", ref.get().getFriend().getFriendAccountId()); + assertEquals(accountUuid(3L), ref.get().getFriend().getFriendAccountId()); } @Test @@ -780,21 +804,34 @@ 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, accountUuid(2L))).thenReturn(true); + Mockito.when(friend.removeFriendByOrdinal(1L, accountUuid(2L), 1)) .thenReturn( java.util.Optional.of( new FriendRosterEntryDto( 1, 7L, 1L, - 2L, - 3L, + accountUuid(2L), + accountUuid(3L), "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)))); + accountUuid(3L), + 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 +840,7 @@ void removeFriendByOrdinalMapsRemovedCanonicalEntry() { service.removeFriendByOrdinal( net.firedevops.firemud.socialgroups.v1.RemoveFriendByOrdinalRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(accountUuid(2L)) .setOrdinal(1) .build(), new StreamObserver<>() { @@ -821,7 +858,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals(true, ref.get().getSuccess()); - assertEquals("3", ref.get().getRemovedFriend().getFriendAccountId()); + assertEquals(accountUuid(3L), ref.get().getRemovedFriend().getFriendAccountId()); } @Test @@ -832,8 +869,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, accountUuid(2L))).thenReturn(true); + Mockito.when(friend.getFriendPresencePolicy(1L, accountUuid(2L))) .thenReturn(new FriendPresencePolicyViewDto(FriendPresenceVisibilityPolicyValue.PRIVATE)); SocialGroupsGrpcService service = new SocialGroupsGrpcService( @@ -843,7 +880,7 @@ void getFriendPresencePolicyMapsCanonicalPolicy() { service.getFriendPresencePolicy( net.firedevops.firemud.socialgroups.v1.GetFriendPresencePolicyRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(accountUuid(2L)) .build(), new StreamObserver<>() { @Override @@ -881,7 +918,7 @@ void getFriendPresencePolicyRejectsMalformedTenantIdBeforeAccessCheck() { service.getFriendPresencePolicy( net.firedevops.firemud.socialgroups.v1.GetFriendPresencePolicyRequest.newBuilder() .setTenantId("abc") - .setAccountId("2") + .setAccountId(accountUuid(2L)) .build(), new StreamObserver<>() { @Override @@ -910,9 +947,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, accountUuid(2L))).thenReturn(true); Mockito.when( - friend.updateFriendPresencePolicy(1L, 2L, FriendPresenceVisibilityPolicyValue.PUBLIC)) + friend.updateFriendPresencePolicy( + 1L, accountUuid(2L), FriendPresenceVisibilityPolicyValue.PUBLIC)) .thenReturn(new FriendPresencePolicyViewDto(FriendPresenceVisibilityPolicyValue.PUBLIC)); SocialGroupsGrpcService service = new SocialGroupsGrpcService( @@ -922,7 +960,7 @@ void updateFriendPresencePolicyMapsCanonicalPolicy() { service.updateFriendPresencePolicy( net.firedevops.firemud.socialgroups.v1.UpdateFriendPresencePolicyRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(accountUuid(2L)) .setVisibilityPolicy( net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC) @@ -956,7 +994,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, accountUuid(2L))).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -965,7 +1003,7 @@ void sendMailRejectsZeroRecipientAccountIdBeforeDispatch() { service.sendMail( net.firedevops.firemud.socialgroups.v1.SendMailRequest.newBuilder() .setTenantId("1") - .setSenderAccountId("2") + .setSenderAccountId(accountUuid(2L)) .setRecipientAccountId("0") .setSubject("hi") .setContent("body") @@ -986,7 +1024,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 +1036,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, accountUuid(2L))).thenReturn(false); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -1007,8 +1045,8 @@ void sendMailReturnsPermissionDeniedForUnauthorizedSender() { service.sendMail( net.firedevops.firemud.socialgroups.v1.SendMailRequest.newBuilder() .setTenantId("1") - .setSenderAccountId("2") - .setRecipientAccountId("3") + .setSenderAccountId(accountUuid(2L)) + .setRecipientAccountId(accountUuid(3L)) .setSubject("hi") .setContent("body") .build(), @@ -1031,4 +1069,77 @@ public void onCompleted() {} assertEquals("Account access required", ref.get().getError().getMessage()); verifyNoInteractions(mail); } + + @Test + void canonicalFriendViewerMustMatchActualCallerEvenWithTenantRoles() { + FriendService friend = Mockito.mock(FriendService.class); + var service = + new SocialGroupsGrpcService( + Mockito.mock(PingService.class), + Mockito.mock(ChatService.class), + Mockito.mock(GuildService.class), + friend, + Mockito.mock(MailService.class), + new SocialAccessGuard(), + new SimpleMeterRegistry()); + net.firedevops.firemud.common.security.SessionContext.setContext( + accountUuid(1L), List.of("platformAdmin"), java.util.Map.of("7", List.of("tenantAdmin"))); + try { + AtomicReference result = new AtomicReference<>(); + service.listFriends( + net.firedevops.firemud.socialgroups.v1.ListFriendsRequest.newBuilder() + .setTenantId("7") + .setAccountId(accountUuid(2L)) + .build(), + new StreamObserver<>() { + public void onNext(ListFriendsResponse value) { + result.set(value); + } + + public void onError(Throwable error) { + throw new AssertionError(error); + } + + public void onCompleted() {} + }); + assertEquals("PERMISSION_DENIED", result.get().getError().getCode()); + verifyNoInteractions(friend); + } finally { + net.firedevops.firemud.common.security.SessionContext.clear(); + } + } + + @Test + void numericFriendViewerFailsBeforeAuthorizationOrServiceDispatch() { + FriendService friend = Mockito.mock(FriendService.class); + SocialAccessGuard guard = Mockito.mock(SocialAccessGuard.class); + var service = + new SocialGroupsGrpcService( + Mockito.mock(PingService.class), + Mockito.mock(ChatService.class), + Mockito.mock(GuildService.class), + friend, + Mockito.mock(MailService.class), + guard, + new SimpleMeterRegistry()); + AtomicReference result = new AtomicReference<>(); + service.listFriends( + net.firedevops.firemud.socialgroups.v1.ListFriendsRequest.newBuilder() + .setTenantId("7") + .setAccountId("2") + .build(), + new StreamObserver<>() { + public void onNext(ListFriendsResponse value) { + result.set(value); + } + + public void onError(Throwable error) { + throw new AssertionError(error); + } + + public void onCompleted() {} + }); + assertEquals("INVALID_ARGUMENT", result.get().getError().getCode()); + verifyNoInteractions(friend, guard); + } } 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..f8b4beeaa4 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.socialgroups.service.impl; +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; import static org.junit.jupiter.api.Assertions.assertNotNull; import net.firedevops.firemud.common.security.JwtUtil; @@ -20,7 +21,7 @@ void setup() { @Test void createTokenReturnsToken() { - VoiceTokenRequestDto request = new VoiceTokenRequestDto(1L, 2L, "guild-1"); + VoiceTokenRequestDto request = new VoiceTokenRequestDto(1L, accountUuid(2L), "guild-1"); VoiceTokenDto dto = service.createToken(request); diff --git a/services/social-groups-service/src/testFixtures/java/net/firedevops/firemud/socialgroups/test/AccountUuidFixtures.java b/services/social-groups-service/src/testFixtures/java/net/firedevops/firemud/socialgroups/test/AccountUuidFixtures.java new file mode 100644 index 0000000000..adc158aaeb --- /dev/null +++ b/services/social-groups-service/src/testFixtures/java/net/firedevops/firemud/socialgroups/test/AccountUuidFixtures.java @@ -0,0 +1,12 @@ +package net.firedevops.firemud.socialgroups.test; + +/** + * Stable ordinary Account UUIDs for fixtures only; ordinals are never runtime identity mappings. + */ +public final class AccountUuidFixtures { + private AccountUuidFixtures() {} + + public static String accountUuid(long fixtureOrdinal) { + return String.format("10000000-0000-4000-8000-%012d", fixtureOrdinal); + } +} diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/JwtAuthFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/JwtAuthFilterTest.java index b07ee0746d..3701fe694d 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/JwtAuthFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/JwtAuthFilterTest.java @@ -1,12 +1,16 @@ package net.firedevops.firemud.springcloudgateway.filter; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.common.security.JwtUtil; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; @@ -14,6 +18,7 @@ import reactor.core.publisher.Mono; class JwtAuthFilterTest { + private static final String ACCOUNT_ID = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; private final JwtUtil jwtUtil = new JwtUtil("testsecretkeytestsecretkeytest1234", 3600000L); private final JwtAuthFilter filter = new JwtAuthFilter(jwtUtil); @@ -27,7 +32,9 @@ void rejectsRequestWithoutToken() { @Test void rejectsRequestWithoutAdminRole() { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("player"))); + String token = + jwtUtil.generateToken( + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("player"))); MockServerHttpRequest.BaseBuilder builder = MockServerHttpRequest.get("/routes/test") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token); @@ -38,7 +45,9 @@ void rejectsRequestWithoutAdminRole() { @Test void allowsRequestWithAdminRole() { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); MockServerHttpRequest.BaseBuilder builder = MockServerHttpRequest.get("/routes/test") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token); @@ -51,7 +60,9 @@ void allowsRequestWithAdminRole() { @Test void rejectsMalformedScopedRolesClaimShape() { - String token = jwtUtil.generateToken("user", Map.of("scopedRoles", List.of("tenantAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "scopedRoles", List.of("tenantAdmin"))); MockServerHttpRequest.BaseBuilder builder = MockServerHttpRequest.get("/routes/test") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token); @@ -61,4 +72,31 @@ void rejectsMalformedScopedRolesClaimShape() { assertEquals(HttpStatus.UNAUTHORIZED, exchange.getResponse().getStatusCode()); } + + @ParameterizedTest + @ValueSource(strings = {"/routes/test", "/api/admin/test"}) + void rejectsDifferentSignedAccountSubjectBeforePrivilegedDispatch(String path) { + String token = + jwtUtil.generateToken( + "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", + Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.get(path) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) + .build()); + AtomicBoolean forwarded = new AtomicBoolean(); + + filter + .filter( + exchange, + e -> { + forwarded.set(true); + return Mono.empty(); + }) + .block(); + + assertEquals(HttpStatus.UNAUTHORIZED, exchange.getResponse().getStatusCode()); + assertFalse(forwarded.get()); + } } diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index c85f46a726..d79dd9ce51 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -5,6 +5,7 @@ import java.io.IOException; import java.net.URI; import java.time.Duration; +import java.util.List; import java.util.Map; import java.util.Objects; import net.firedevops.firemud.cache.ScreenBufferService; @@ -126,6 +127,11 @@ static synchronized void stopTestServices() { void clearSharedRuntimeState() throws Exception { ensureTestServicesStarted(); STACK.freshGameplayBaseline(TENANT_ID, DEFAULT_GAME_INSTANCE_ID, ACCOUNT_ID, 7L, ACCOUNT_ID); + entityStub() + .setCharacters( + List.of("Emberline", "Sora", "Nyx").stream() + .map(ChatTestFixtures::characterByName) + .toList()); } @Test @@ -789,19 +795,22 @@ private static void awaitGameSessionReadiness(int gameSessionPort) { private void seedLiveTargetSession() { STACK.seedLiveSession( - 90210L, - TENANT_ID, - Long.parseLong(ChatTestFixtures.PLAYER_SORA), - "sora@example.com", - Long.parseLong(ChatTestFixtures.PLAYER_SORA), - "Sora", - DEMO_WORLD_INSTANCE_ID, - LookTestFixtures.ROOM_ID, - "target-jwt", - "demo", - "production", - 1L, - "SHARED"); + new SessionContext( + 90210L, + TENANT_ID, + AccountRuntimeStubServer.accountUuidForTestFixture(SORA_ACCOUNT_ID), + "sora@example.com", + SORA_ACCOUNT_ID, + "Sora", + DEMO_WORLD_INSTANCE_ID, + LookTestFixtures.ROOM_ID, + "target-jwt", + null, + DEMO_WORLD_INSTANCE_ID, + "demo", + "production", + 1L, + "SHARED")); } private static GatewayHolder startGateway(int gameSessionPort) { From 94370083f3e49318c394af9525f773ffc4310463 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:31:07 +1300 Subject: [PATCH 04/34] Reconcile ordinary Account UUID sources and receiving proofs --- services/account-service/build.gradle.kts | 19 + .../service/impl/AccountGrpcService.java | 15 +- .../service/impl/AccountServiceImpl.java | 79 ++- .../src/main/resources/openapi.yaml | 3 + .../AccountApplicationIntegrationTest.java | 526 +++++++++++++++++- .../InternalRuntimeControllerTest.java | 14 +- .../RemovedExternalAccountRouteHttpTest.java | 3 +- .../security/GrpcJwtAuthInterceptorTest.java | 5 +- .../service/impl/AccountGrpcServiceTest.java | 49 ++ .../service/impl/AccountServiceImplTest.java | 357 +++++++++++- .../firemud/common/security/JwtClaims.java | 2 +- .../common/security/JwtClaimsTest.java | 35 ++ .../text/CommunicationCommandHandler.java | 14 + ...ommunicationWebSocketCrossServiceTest.java | 5 + .../text/CommunicationCommandHandlerTest.java | 74 ++- .../command/text/PlayCommandHandlerTest.java | 99 +--- .../impl/GameSessionGrpcServiceTest.java | 1 - .../security/SocialAccessGuard.java | 14 + .../service/impl/GuildServiceImpl.java | 39 +- .../service/impl/SocialGroupsGrpcService.java | 15 +- .../controller/GuildControllerTest.java | 27 +- .../controller/PingControllerTest.java | 8 +- .../controller/VoiceChatControllerTest.java | 2 +- .../security/SocialAccessGuardTest.java | 24 + .../service/impl/GuildServiceImplTest.java | 204 +++++-- .../impl/SocialGroupsGrpcServiceTest.java | 137 ++++- 26 files changed, 1552 insertions(+), 218 deletions(-) diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index e088cffbae..08cca8ea6a 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -87,6 +87,7 @@ dependencies { testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) integrationTestImplementation(project(path = ":game-session-service", configuration = "gameSessionClassesProof")) + integrationTestImplementation(project(":social-groups-service")) integrationTestImplementation(testFixtures(project(":account-service"))) integrationTestImplementation(testFixtures(project(":logging-admin-service"))) } @@ -108,6 +109,22 @@ val loggingAdminTestArtifacts = loggingAdminProjectArtifacts("testRuntimeClasspa val loggingAdminIntegrationTestArtifacts = loggingAdminProjectArtifacts("integrationTestRuntimeClasspath") +// Exercise the actual Social guard/handler while retaining Account's application and Flyway resources. +val socialIntegrationTestArtifacts = configurations + .getByName("integrationTestRuntimeClasspath") + .incoming.artifactView { + componentFilter { componentId -> + componentId is ProjectComponentIdentifier + && componentId.projectPath == ":social-groups-service" + } + }.artifacts + +val extractSocialIntegrationTestClasses = tasks.register("extractSocialIntegrationTestClasses") { + dependsOn(socialIntegrationTestArtifacts.artifactFiles) + archives.from(socialIntegrationTestArtifacts.artifactFiles) + destinationDirectory.set(layout.buildDirectory.dir("account-test-classpath/social-integration")) +} + val extractLoggingAdminTestClasses = tasks.register("extractLoggingAdminTestClasses") { dependsOn(loggingAdminTestArtifacts.artifactFiles) @@ -142,6 +159,8 @@ tasks.named("integrationTest") { .withPathSensitivity(PathSensitivity.RELATIVE) val loggingArtifacts = loggingAdminIntegrationTestArtifacts.artifactFiles classpath = classpath.filter { it !in loggingArtifacts } + files(extractLoggingAdminIntegrationTestClasses) + val socialArtifacts = socialIntegrationTestArtifacts.artifactFiles + classpath = classpath.filter { it !in socialArtifacts } + files(extractSocialIntegrationTestClasses) } // Owner proof exports classes and its required registry script without Account application or 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 c674157e24..97872fc3a1 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 @@ -451,7 +451,20 @@ public void verifyEmailLoginOtp( AuthenticateResponse.newBuilder() .setError(appError("VerifyEmailLoginOtp", "INVALID_ARGUMENT", ex.getMessage())) .build()); - } catch (AuthenticationException | IllegalArgumentException ex) { + } catch (AuthenticationException ex) { + responseObserver.onNext( + AuthenticateResponse.newBuilder() + .setError( + appError( + "VerifyEmailLoginOtp", + "AUTH_UNAVAILABLE".equals(ex.getCode()) + ? "AUTH_UNAVAILABLE" + : AuthenticationErrorCodes.INVALID_CREDENTIALS, + "AUTH_UNAVAILABLE".equals(ex.getCode()) + ? AUTHORITY_UNAVAILABLE_MESSAGE + : "Invalid credentials")) + .build()); + } catch (IllegalArgumentException ex) { responseObserver.onNext( AuthenticateResponse.newBuilder() .setError( 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 58bd605806..273eab6c88 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 @@ -572,7 +572,8 @@ public DirectTextJoinScope issueDirectTextConnectScope( || !caller.playableStateScope().equals(target.playableStateScope())) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); } - requireAuthenticationEligible(requireAccount(caller.accountId())); + Account account = requireAccount(caller.accountId()); + requireAuthenticationEligible(account); RuntimeRealmTarget current = requireRealmTarget(target.tenantId(), target.worldSlug(), target.realmSlug()); if (!isPublicProductionRealm(current)) { @@ -595,11 +596,10 @@ public DirectTextJoinScope issueDirectTextConnectScope( } Instant evaluatedAt = Instant.now(); Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); + requireAuthenticationAccountUuid(account); String scopeId = mintAndRetainConnectScope( - new BootstrapContext( - caller.accountId(), - requireAuthenticationAccountUuid(requireAccount(caller.accountId())).toString()), + new BootstrapContext(caller.accountId(), account.getAccountUuid()), current, evaluatedAt, expiresAt); @@ -1300,18 +1300,23 @@ private BootstrapContext requireBootstrapContext(String bootstrapToken) { "CONNECT_CONTEXT_INVALID", "Missing bootstrap token", "Invalid bootstrap token"); + UUID subject = + claims.get("sub") instanceof String text ? AccountUuidText.parseOrNull(text) : null; + UUID accountUuid = + claims.get("accountId") instanceof String text ? AccountUuidText.parseOrNull(text) : null; + if (subject == null || accountUuid == null || !subject.equals(accountUuid)) { + throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Invalid bootstrap token"); + } + final Long accountId; try { - String accountUuid = - JwtClaims.requireSignedGameplayAccountUuid( - claims, "signed token account subject mismatch"); - long accountId = resolveAccountStorageId(UUID.fromString(accountUuid)); - if (!sessionService.isAccountSessionActive(accountId, bootstrapToken)) { - throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Bootstrap token expired"); - } - return new BootstrapContext(accountId, accountUuid); - } catch (IllegalArgumentException | IllegalStateException ex) { - throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Invalid bootstrap token", ex); + accountId = resolveAccountStorageId(accountUuid); + } catch (IllegalArgumentException | IllegalStateException | DataAccessException ex) { + throw new AuthenticationException("AUTH_UNAVAILABLE", "Account authority is unavailable", ex); } + if (!sessionService.isAccountSessionActive(accountId, bootstrapToken)) { + throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Bootstrap token expired"); + } + return new BootstrapContext(accountId, accountUuid); } private RuntimeRealmTarget requireRealmTarget( @@ -1544,11 +1549,11 @@ private String mintConnectScopeId( Instant expiresAt) { long expirationMs = Math.max(1L, expiresAt.toEpochMilli() - evaluatedAt.toEpochMilli()); return mintToken( - bootstrapContext.accountUuid(), + bootstrapContext.accountUuid().toString(), expirationMs, Map.ofEntries( Map.entry("aud", "bootstrap-connect-scope"), - Map.entry("accountId", bootstrapContext.accountUuid()), + Map.entry("accountId", bootstrapContext.accountUuid().toString()), Map.entry("tenantId", realm.tenantId()), Map.entry("realmId", realm.realmId().toString()), Map.entry("worldSlug", realm.worldSlug()), @@ -1574,6 +1579,13 @@ private String mintConnectScopeId( private String mintAndRetainConnectScope( BootstrapContext caller, RuntimeRealmTarget realm, Instant evaluatedAt, Instant expiresAt) { + try { + if (!Long.valueOf(caller.accountId()).equals(resolveAccountStorageId(caller.accountUuid()))) { + throw new IllegalStateException("Scope Account UUID resolved to a different owner"); + } + } catch (IllegalArgumentException | IllegalStateException | DataAccessException ex) { + throw new AuthenticationException("AUTH_UNAVAILABLE", "Account authority is unavailable", ex); + } String connectScopeId = mintConnectScopeId(caller, realm, evaluatedAt, expiresAt); if (isPublicProductionRealm(realm)) { VerifiedJoinScope pending = @@ -1632,21 +1644,32 @@ private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { if (evaluatedAt == null) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); } - long accountId = resolveAccountStorageId(UUID.fromString(routingClaims.accountId())); + UUID realmId = requireCanonicalRealmId(claims.get("realmId")); + String namespace = + JwtClaims.requireText(claims.get("playableStateNamespaceId"), "playableStateNamespaceId"); + String scope = JwtClaims.requireText(claims.get("playableStateScope"), "playableStateScope"); + long catalogRevision = requirePositiveLong(claims.get("catalogRevision"), "catalogRevision"); + final Long accountId; + try { + accountId = resolveAccountStorageId(UUID.fromString(routingClaims.accountId())); + } catch (IllegalArgumentException | IllegalStateException | DataAccessException ex) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Account authority is unavailable", ex); + } return new ConnectScopeContext( accountId, routingClaims.tenantId(), - requireCanonicalRealmId(claims.get("realmId")), + realmId, routingClaims.worldSlug(), routingClaims.realmSlug(), - JwtClaims.requireText(claims.get("playableStateNamespaceId"), "playableStateNamespaceId"), - JwtClaims.requireText(claims.get("playableStateScope"), "playableStateScope"), + namespace, + scope, routingClaims.gameInstanceId(), - requirePositiveLong(claims.get("catalogRevision"), "catalogRevision"), + catalogRevision, routingClaims.pointerVersion(), evaluatedAt, connectScopeExpiresAt); - } catch (IllegalArgumentException | IllegalStateException ex) { + } catch (IllegalArgumentException ex) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE, ex); } } @@ -2041,17 +2064,17 @@ private Account requireAccount(Long accountId) { } private UUID requireAuthenticationAccountUuid(Account account) { - requireAuthenticationPersistedIdentity(account); - UUID accountUuid = account.getAccountUuid(); try { + requireAuthenticationPersistedIdentity(account); + UUID accountUuid = account.getAccountUuid(); Long storageId = resolveAccountStorageId(accountUuid); if (!Objects.equals(account.getId(), storageId)) { throw new IllegalStateException("Account identity does not match its persisted owner"); } - } catch (IllegalArgumentException | IllegalStateException ex) { - throw new IllegalStateException("Account identity does not match its persisted owner", ex); + return accountUuid; + } catch (IllegalArgumentException | IllegalStateException | DataAccessException ex) { + throw new AuthenticationException("AUTH_UNAVAILABLE", "Account authority is unavailable", ex); } - return accountUuid; } /** Resolves a canonical public identity at the Account persistence boundary only. */ @@ -3206,7 +3229,7 @@ public void afterCommit() { }); } - private record BootstrapContext(long accountId, String accountUuid) {} + private record BootstrapContext(long accountId, UUID accountUuid) {} private record JoinAuditPayload( long accountId, diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 3d8cdc7805..37c348a10e 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -138,6 +138,7 @@ components: properties: connectScopeId: type: string + description: Opaque signed scope with canonical UUID Account identity; obtain fresh scope through discovery rather than interpreting its payload. requestId: type: string required: [connectScopeId, requestId] @@ -154,6 +155,7 @@ components: type: string connectScopeId: type: string + description: Opaque signed scope with canonical UUID Account identity; obtain fresh scope through discovery rather than interpreting its payload. jti: type: string requestId: @@ -214,6 +216,7 @@ components: type: string connectScopeId: type: string + description: Opaque signed scope with canonical UUID Account identity; obtain fresh scope through discovery rather than interpreting its payload. BootstrapCharacterDto: type: object properties: diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index aa8daa9904..753ef34a70 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -42,7 +42,8 @@ GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, - GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH + GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH, + "firemud.mail.verification-url=https://account.test/verify-email?token=%s" }) class AccountApplicationIntegrationTest { private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); @@ -65,6 +66,15 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private JwtUtil jwtUtil; @Autowired private DSLContext dsl; @Autowired private AccountService accountService; + + @org.springframework.test.context.bean.override.mockito.MockitoSpyBean + private net.firedevops.firemud.accountservice.repository.AccountRepository accountRepository; + + @Autowired private org.springframework.transaction.PlatformTransactionManager transactionManager; + + @Autowired + private org.springframework.data.redis.core.RedisTemplate redisTemplate; + private final JsonMapper jsonMapper = JsonMapper.builder().build(); @MockitoBean private EntityManagementClient entityManagementClient; @@ -160,7 +170,8 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws } @Test - void ordinaryAuthenticationReturnsPersistedAccountUuidInResponseAndValidatedJwt() throws Exception { + void ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity() + throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); String username = "auth-uuid-" + suffix; String email = username + "@example.com"; @@ -207,9 +218,7 @@ void ordinaryAuthenticationReturnsPersistedAccountUuidInResponseAndValidatedJwt( .header(HttpHeaders.CONTENT_TYPE, "application/json") .POST( HttpRequest.BodyPublishers.ofString( - "{\"username\":\"" - + username - + "\",\"password\":\"password123\"}")) + "{\"username\":\"" + username + "\",\"password\":\"password123\"}")) .build(); HttpResponse authenticationResponse = @@ -223,8 +232,153 @@ void ordinaryAuthenticationReturnsPersistedAccountUuidInResponseAndValidatedJwt( var claims = jwtUtil.parseToken(token).getPayload(); assertThat(claims.getSubject()).isEqualTo(persistedAccountUuid.toString()); assertThat(claims.get("accountId", String.class)).isEqualTo(persistedAccountUuid.toString()); - assertThat(authenticationResponse.body()) - .doesNotContain("\"accountId\":" + numericAccountId); + String otherAccountUuid = + accountService + .createAccount( + new net.firedevops.firemud.accountservice.dto.CreateAccountRequest( + "guild-other-" + suffix, + "guild-other-" + suffix + "@example.com", + "password123")) + .id(); + assertOrdinaryCredentialPreservesSocialGuildSelf( + token, persistedAccountUuid.toString(), otherAccountUuid); + + HttpRequest bootstrapRequest = + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/auth/player-bootstrap")) + .header(HttpHeaders.CONTENT_TYPE, "application/json") + .POST( + HttpRequest.BodyPublishers.ofString( + jsonMapper.writeValueAsString( + java.util.Map.of("accountIdentifier", username, "secret", "password123")))) + .build(); + HttpResponse bootstrapResponse = + HTTP_CLIENT.send(bootstrapRequest, HttpResponse.BodyHandlers.ofString()); + assertThat(bootstrapResponse.statusCode()).isEqualTo(200); + var bootstrapData = jsonMapper.readTree(bootstrapResponse.body()).path("data"); + assertThat(bootstrapData.path("accountId").asText()).isEqualTo(persistedAccountUuid.toString()); + var bootstrapClaims = + jwtUtil.parseToken(bootstrapData.path("bootstrapToken").asText()).getPayload(); + assertThat(bootstrapClaims.getSubject()).isEqualTo(persistedAccountUuid.toString()); + assertThat(bootstrapClaims.get("accountId", String.class)) + .isEqualTo(persistedAccountUuid.toString()); + org.mockito.Mockito.when(gameSessionClient.listGameplayWorlds()) + .thenReturn(java.util.List.of()); + String passwordBootstrap = bootstrapData.path("bootstrapToken").asText(); + assertThat(bootstrapWorlds(passwordBootstrap).statusCode()).isEqualTo(200); + invalidateBootstrapSession(numericAccountId, passwordBootstrap); + HttpResponse expiredPassword = bootstrapWorlds(passwordBootstrap); + assertThat(expiredPassword.statusCode()).isEqualTo(401); + assertThat(expiredPassword.body()).contains("CONNECT_CONTEXT_INVALID"); + + accountService.requestEmailVerification(email); + String verificationToken = + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT token FROM email_verification_token WHERE account_id=?", + numericAccountId), + "Expected persisted email-verification record") + .get(0, String.class); + accountService.verifyEmail( + new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest(verificationToken)); + accountService.requestEmailLoginOtp(email); + var messages = + org.mockito.ArgumentCaptor.forClass(org.springframework.mail.SimpleMailMessage.class); + org.mockito.Mockito.verify(mailSender, org.mockito.Mockito.atLeastOnce()) + .send(messages.capture()); + String otpBody = + messages.getAllValues().stream() + .filter(message -> "Your FireMUD login code".equals(message.getSubject())) + .filter( + message -> { + String[] recipients = message.getTo(); + return recipients != null && java.util.Arrays.asList(recipients).contains(email); + }) + .map( + message -> + java.util.Objects.requireNonNull(message.getText(), "Expected OTP email body")) + .findFirst() + .orElseThrow(); + var matcher = java.util.regex.Pattern.compile("\\b(\\d{6})\\b").matcher(otpBody); + assertThat(matcher.find()).isTrue(); + String otp = matcher.group(1); + HttpRequest otpRequest = + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/auth/player-bootstrap")) + .header(HttpHeaders.CONTENT_TYPE, "application/json") + .POST( + HttpRequest.BodyPublishers.ofString( + jsonMapper.writeValueAsString( + java.util.Map.of("accountIdentifier", email, "secret", otp)))) + .build(); + HttpResponse otpResponse = + HTTP_CLIENT.send(otpRequest, HttpResponse.BodyHandlers.ofString()); + assertThat(otpResponse.statusCode()).isEqualTo(200); + var otpData = jsonMapper.readTree(otpResponse.body()).path("data"); + assertThat(otpData.path("accountId").asText()).isEqualTo(persistedAccountUuid.toString()); + String otpBootstrap = otpData.path("bootstrapToken").asText(); + var otpClaims = jwtUtil.parseToken(otpBootstrap).getPayload(); + assertThat(otpClaims.getSubject()).isEqualTo(persistedAccountUuid.toString()); + assertThat(otpClaims.get("accountId", String.class)).isEqualTo(persistedAccountUuid.toString()); + assertThat( + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM account_email_login_challenge WHERE account_id=?", + numericAccountId), + "Expected challenge-count record") + .get(0, Long.class)) + .isZero(); + assertThat(bootstrapWorlds(otpBootstrap).statusCode()).isEqualTo(200); + invalidateBootstrapSession(numericAccountId, otpBootstrap); + assertThat(bootstrapWorlds(otpBootstrap).statusCode()).isEqualTo(401); + + // Obtain a fresh real challenge: bootstrap issuance consumed the preceding one. + accountService.requestEmailLoginOtp(email); + var loginMessages = + org.mockito.ArgumentCaptor.forClass(org.springframework.mail.SimpleMailMessage.class); + org.mockito.Mockito.verify(mailSender, org.mockito.Mockito.atLeastOnce()) + .send(loginMessages.capture()); + String loginOtpBody = + loginMessages.getAllValues().stream() + .filter(message -> "Your FireMUD login code".equals(message.getSubject())) + .filter( + message -> { + String[] recipients = message.getTo(); + return recipients != null && java.util.Arrays.asList(recipients).contains(email); + }) + .map( + message -> + java.util.Objects.requireNonNull(message.getText(), "Expected login OTP body")) + .reduce((earlier, latest) -> latest) + .orElseThrow(); + var loginMatcher = java.util.regex.Pattern.compile("\\b(\\d{6})\\b").matcher(loginOtpBody); + assertThat(loginMatcher.find()).isTrue(); + HttpRequest otpLoginRequest = + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/auth/login")) + .header(HttpHeaders.CONTENT_TYPE, "application/json") + .POST( + HttpRequest.BodyPublishers.ofString( + jsonMapper.writeValueAsString( + java.util.Map.of("username", email, "password", loginMatcher.group(1))))) + .build(); + HttpResponse otpLoginResponse = + HTTP_CLIENT.send(otpLoginRequest, HttpResponse.BodyHandlers.ofString()); + assertThat(otpLoginResponse.statusCode()).isEqualTo(200); + var loginData = jsonMapper.readTree(otpLoginResponse.body()).path("data"); + assertThat(loginData.path("accountId").asText()).isEqualTo(persistedAccountUuid.toString()); + var loginClaims = jwtUtil.parseToken(loginData.path("authToken").asText()).getPayload(); + assertThat(loginClaims.getSubject()).isEqualTo(persistedAccountUuid.toString()); + assertThat(loginClaims.get("accountId", String.class)) + .isEqualTo(persistedAccountUuid.toString()); + assertThat(loginClaims.getAudience()).containsExactly("control-ui"); + assertOrdinaryCredentialPreservesSocialGuildSelf( + loginData.path("authToken").asText(), persistedAccountUuid.toString(), otherAccountUuid); + assertThat( + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM account_email_login_challenge WHERE account_id=?", + numericAccountId), + "Expected consumed ordinary-login challenge count") + .get(0, Long.class)) + .isZero(); assertThat( dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", numericAccountId) @@ -241,13 +395,367 @@ void ordinaryAuthenticationReturnsPersistedAccountUuidInResponseAndValidatedJwt( "SELECT account_uuid_provenance FROM accounts WHERE id = ?", numericAccountId) .fetchOne(0, String.class)) .isEqualTo(provenance); + // Controlled persisted role assignment, not a synthetic privileged JWT or scoped-role issuer. + new org.springframework.transaction.support.TransactionTemplate(transactionManager) + .execute( + status -> { + var owner = accountRepository.findByIdForUpdate(numericAccountId).orElseThrow(); + owner.setRole("moderator"); + accountRepository.save(owner); + return null; + }); + HttpResponse moderatorResponse = + HTTP_CLIENT.send(authenticationRequest, HttpResponse.BodyHandlers.ofString()); + assertThat(moderatorResponse.statusCode()).isEqualTo(200); + String moderatorToken = + jsonMapper.readTree(moderatorResponse.body()).path("data").path("authToken").asText(); + assertOrdinaryModeratorPreservesGuildTenantAccess( + moderatorToken, persistedAccountUuid.toString(), otherAccountUuid); + + org.mockito.Mockito.doThrow( + new org.springframework.dao.DataAccessResourceFailureException( + "controlled owner readback outage")) + .when(accountRepository) + .findByAccountUuid(persistedAccountUuid); + HttpResponse unavailable = + HTTP_CLIENT.send(authenticationRequest, HttpResponse.BodyHandlers.ofString()); + assertThat(unavailable.statusCode()).isEqualTo(503); + assertThat(jsonMapper.readTree(unavailable.body()).path("error").path("code").asText()) + .isEqualTo("AUTH_UNAVAILABLE"); + assertThat(jsonMapper.readTree(unavailable.body()).path("data").path("authToken").asText()) + .isEmpty(); + } + + @Test + void browserAndControlledDirectScopesRetainUuidClaimsAndPrivateJoinRows() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String username = "scope-" + suffix; + var account = + accountService.createAccount( + new net.firedevops.firemud.accountservice.dto.CreateAccountRequest( + username, username + "@example.com", "password123")); + var persistedAccount = + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT id FROM accounts WHERE account_uuid=?", UUID.fromString(account.id())), + "Expected persisted Account"); + long row = + java.util.Objects.requireNonNull( + persistedAccount.get(0, Long.class), "Expected persisted Account storage key"); + long tenant = 500000000L + Integer.toUnsignedLong(suffix.hashCode()); + dsl.execute( + "INSERT INTO subscription(account_id,plan_id,status,tenant_id,entitlement_version) VALUES(?,'scope-proof','active',?,1)", + row, + tenant); + String realm = UUID.randomUUID().toString(); + String namespace = UUID.randomUUID().toString(); + var target = + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("scope-proof") + .setRealmSlug("production") + .setDisplayName("Scope proof") + .setTenantId(Long.toString(tenant)) + .setGameInstanceId("44") + .setRealmId(realm) + .setPlayableStateNamespaceId(namespace) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build(); + org.mockito.Mockito.when(gameSessionClient.listGameplayRealms("scope-proof")) + .thenReturn(java.util.List.of(target)); + org.mockito.Mockito.when( + gameSessionClient.getAdmissionPointer(tenant, "scope-proof", "production")) + .thenReturn( + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("scope-proof") + .setRealmSlug("production") + .setTenantId(Long.toString(tenant)) + .setGameInstanceId("44") + .setRealmId(realm) + .setPlayableStateNamespaceId(namespace) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build()); + var bootstrap = accountService.issuePlayerBootstrap(username, "password123"); + String browser = + accountService + .listBootstrapRealms(bootstrap.bootstrapToken(), "scope-proof") + .getFirst() + .connectScopeId(); + var player = + net.firedevops.firemud.shared.v1.PlayerExecutionContext.newBuilder() + .setAccountId(account.id()) + .setTenantId(Long.toString(tenant)) + .setRealmId(realm) + .setPlayableStateNamespaceId(namespace) + .setPlayableStateScope("SHARED") + .setGameInstanceId("44") + .setSessionId("controlled-session") + .setRequestId("scope-direct-" + suffix) + .build(); + var request = + net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest.newBuilder() + .setPlayerContext(player) + .setTenantId(Long.toString(tenant)) + .setRealmId(realm) + .setWorldSlug("scope-proof") + .setRealmSlug("production") + .setPlayableStateNamespaceId(namespace) + .setPlayableStateScope("SHARED") + .setGameInstanceId("44") + .setCatalogRevision(23L) + .setPointerVersion(17L) + .build(); + var response = + new java.util.concurrent.atomic.AtomicReference< + net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse>(); + var receiver = + new net.firedevops.firemud.accountservice.service.impl.AccountGrpcService( + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.service.PingService.class), + accountService, + null, + "test"); + var context = + io.grpc.Context.ROOT.withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-session-service", + "test", + "game-session-service")); + context.run( + () -> + receiver.issueDirectTextConnectScope( + request, + new io.grpc.stub.StreamObserver<>() { + @Override + public void onNext( + net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable error) { + org.junit.jupiter.api.Assertions.fail(error); + } + + @Override + public void onCompleted() {} + })); + var directResponse = + java.util.Objects.requireNonNull(response.get(), "Expected controlled direct response"); + assertThat(directResponse.hasError()).isFalse(); + String direct = directResponse.getConnectScopeId(); + var scopes = + new net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository(dsl); + for (String token : java.util.List.of(browser, direct)) { + var claims = jwtUtil.parseToken(token).getPayload(); + assertThat(claims.getSubject()).isEqualTo(account.id()); + assertThat(claims.get("accountId", String.class)).isEqualTo(account.id()); + var retained = scopes.find(token).orElseThrow(); + assertThat(retained.accountId()).isEqualTo(row); + assertThat(retained.snapshotDigest()) + .isEqualTo(net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope(retained)); + var held = + org.junit.jupiter.api.Assertions.assertThrows( + net.firedevops.firemud.accountservice.service.exception.AuthenticationException.class, + () -> + accountService.issueConnectToken( + bootstrap.bootstrapToken(), + new net.firedevops.firemud.accountservice.dto.ConnectTokenRequest( + token, "held-" + suffix))); + assertThat(held.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(scopes.find(token)).contains(retained); + } + var browserJoin = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + browser, "scope-browser-" + suffix); + var first = accountService.joinPublicProduction(bootstrap.bootstrapToken(), browserJoin); + assertThat(first.success()).isTrue(); + assertThat( + accountService.joinPublicProduction(bootstrap.bootstrapToken(), browserJoin).replayed()) + .isTrue(); + var caller = + new net.firedevops.firemud.accountservice.dto.DirectTextCallerContext( + row, + tenant, + UUID.fromString(realm), + namespace, + "SHARED", + 44L, + "controlled-session", + "scope-direct-" + suffix); + var directJoin = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + direct, caller.requestId()); + assertThat(accountService.joinPublicProductionFromGameSession(caller, directJoin).success()) + .isTrue(); + assertThat(accountService.joinPublicProductionFromGameSession(caller, directJoin).replayed()) + .isTrue(); + assertThat(scopes.find(browser)).isPresent(); + assertThat(scopes.find(direct)).isPresent(); + } + + private void assertOrdinaryCredentialPreservesSocialGuildSelf( + String token, String accountUuid, String otherAccountUuid) { + var guild = + org.mockito.Mockito.mock(net.firedevops.firemud.socialgroups.service.GuildService.class); + org.mockito.Mockito.when(guild.createGuild(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + net.firedevops.firemud.socialgroups.dto.CreateGuildRequest request = + invocation.getArgument(0); + return new net.firedevops.firemud.socialgroups.dto.GuildDto( + 91L, + request.tenantId(), + request.name(), + request.ownerAccountId(), + java.time.Instant.now()); + }); + assertThat(jwtUtil.parseToken(token).getPayload().get("globalRoles")) + .isEqualTo(java.util.List.of()); + var same = invokeSocialCreateGuild(token, accountUuid, guild); + assertThat(same.hasError()).isFalse(); + assertThat(same.getGuildId()).isEqualTo("91"); + org.mockito.Mockito.verify(guild) + .createGuild( + new net.firedevops.firemud.socialgroups.dto.CreateGuildRequest( + 7L, accountUuid, "credential guild")); + org.mockito.Mockito.clearInvocations(guild); + var other = invokeSocialCreateGuild(token, otherAccountUuid, guild); + assertThat(other.getError().getCode()).isEqualTo("PERMISSION_DENIED"); + for (String malformed : + java.util.List.of( + "11", "00000000-0000-0000-0000-000000000000", "10000000-0000-4000-8000-00000000000A")) { + assertThat(invokeSocialCreateGuild(token, malformed, guild).getError().getCode()) + .isEqualTo("INVALID_ARGUMENT"); + } + org.mockito.Mockito.verifyNoInteractions(guild); + } + + private void assertOrdinaryModeratorPreservesGuildTenantAccess( + String token, String accountUuid, String other) { + var guild = + org.mockito.Mockito.mock(net.firedevops.firemud.socialgroups.service.GuildService.class); + org.mockito.Mockito.when(guild.createGuild(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + net.firedevops.firemud.socialgroups.dto.CreateGuildRequest request = + invocation.getArgument(0); + return new net.firedevops.firemud.socialgroups.dto.GuildDto( + 92L, + request.tenantId(), + request.name(), + request.ownerAccountId(), + java.time.Instant.now()); + }); + assertThat(jwtUtil.parseToken(token).getPayload().get("globalRoles")) + .isEqualTo(java.util.List.of("moderator")); + assertThat(invokeSocialCreateGuild(token, other, guild).hasError()).isFalse(); + org.mockito.Mockito.verify(guild) + .createGuild( + new net.firedevops.firemud.socialgroups.dto.CreateGuildRequest( + 7L, other, "credential guild")); + net.firedevops.firemud.common.security.SessionContext.clear(); + try { + net.firedevops.firemud.common.security.SessionClaims.fromJwt(jwtUtil.parseToken(token)) + .applyToSession(); + var guard = new net.firedevops.firemud.socialgroups.security.SocialAccessGuard(); + assertThat(guard.hasAccountAccess(7L, accountUuid)).isTrue(); + assertThat(guard.hasAccountAccess(7L, other)).isFalse(); + assertThat(guard.hasGuildOwnerAccess(7L, other)).isTrue(); + } finally { + net.firedevops.firemud.common.security.SessionContext.clear(); + } + } + + private net.firedevops.firemud.socialgroups.v1.CreateGuildResponse invokeSocialCreateGuild( + String token, String owner, net.firedevops.firemud.socialgroups.service.GuildService guild) { + var response = + new java.util.concurrent.atomic.AtomicReference< + net.firedevops.firemud.socialgroups.v1.CreateGuildResponse>(); + var metrics = new io.micrometer.core.instrument.simple.SimpleMeterRegistry(); + try { + var receiver = + new net.firedevops.firemud.socialgroups.service.impl.SocialGroupsGrpcService( + org.mockito.Mockito.mock( + net.firedevops.firemud.socialgroups.service.PingService.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.socialgroups.service.ChatService.class), + guild, + org.mockito.Mockito.mock( + net.firedevops.firemud.socialgroups.service.FriendService.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.socialgroups.service.MailService.class), + new net.firedevops.firemud.socialgroups.security.SocialAccessGuard(), + metrics); + net.firedevops.firemud.common.security.SessionContext.clear(); + try { + net.firedevops.firemud.common.security.SessionClaims.fromJwt(jwtUtil.parseToken(token)) + .applyToSession(); + receiver.createGuild( + net.firedevops.firemud.socialgroups.v1.CreateGuildRequest.newBuilder() + .setTenantId("7") + .setOwnerAccountId(owner) + .setName("credential guild") + .build(), + new io.grpc.stub.StreamObserver<>() { + @Override + public void onNext(net.firedevops.firemud.socialgroups.v1.CreateGuildResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable error) { + org.junit.jupiter.api.Assertions.fail(error); + } + + @Override + public void onCompleted() {} + }); + } finally { + net.firedevops.firemud.common.security.SessionContext.clear(); + } + } finally { + metrics.close(); + } + return java.util.Objects.requireNonNull(response.get(), "Expected Social CreateGuild response"); + } + + private HttpResponse bootstrapWorlds(String token) throws Exception { + HttpRequest request = + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/auth/bootstrap/worlds")) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) + .GET() + .build(); + return HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + } + + private void invalidateBootstrapSession(long accountId, String token) throws Exception { + String hash = + java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(token.getBytes(java.nio.charset.StandardCharsets.UTF_8))); + assertThat(redisTemplate.delete("session:auth:account:" + accountId + ":" + hash)).isTrue(); } @Test void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws Exception { + String accountUuid = java.util.UUID.randomUUID().toString(); String token = jwtUtil.generateToken( - "operator", java.util.Map.of("globalRoles", java.util.List.of("platformAdmin"))); + accountUuid, + java.util.Map.of( + "accountId", accountUuid, "globalRoles", java.util.List.of("platformAdmin"))); HttpRequest request = HttpRequest.newBuilder( URI.create("http://localhost:" + port + "/accounts/not-a-uuid/export")) @@ -296,7 +804,7 @@ void updateProfileRejectsZeroTenantIdWithInvalidArgumentEnvelope() throws Except .PUT( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":0,"accountId":2,"displayName":"demo","bio":"bio","presenceVisibilityPolicy":"PRIVATE"} + {"tenantId":0,"accountId":"b8d093f7-cb70-40ed-9fac-3c82d4bf28f1","displayName":"demo","bio":"bio","presenceVisibilityPolicy":"PRIVATE"} """)) .build(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/InternalRuntimeControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/InternalRuntimeControllerTest.java index ebc10dc331..7bb283741a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/InternalRuntimeControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/InternalRuntimeControllerTest.java @@ -44,7 +44,12 @@ void clear() { void grantRealmAccessRejectsZeroAccountIdBeforeDispatch() throws Exception { String token = jwtUtil.generateToken( - "user", java.util.Map.of("globalRoles", java.util.List.of("platformAdmin"))); + "f22f310d-5464-45f0-9dc4-c37353004403", + java.util.Map.of( + "accountId", + "f22f310d-5464-45f0-9dc4-c37353004403", + "globalRoles", + java.util.List.of("platformAdmin"))); mockMvc .perform( @@ -74,7 +79,12 @@ void grantRealmAccessRejectsZeroAccountIdBeforeDispatch() throws Exception { void revokeRealmAccessRejectsMalformedAccountIdBeforeDispatch() throws Exception { String token = jwtUtil.generateToken( - "user", java.util.Map.of("globalRoles", java.util.List.of("platformAdmin"))); + "f22f310d-5464-45f0-9dc4-c37353004403", + java.util.Map.of( + "accountId", + "f22f310d-5464-45f0-9dc4-c37353004403", + "globalRoles", + java.util.List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/RemovedExternalAccountRouteHttpTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/RemovedExternalAccountRouteHttpTest.java index bf6c0b8ed9..8ab1612825 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/RemovedExternalAccountRouteHttpTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/RemovedExternalAccountRouteHttpTest.java @@ -59,7 +59,8 @@ void removedExternalRouteRequiresAuthenticationThenUsesDefaultNotFoundErrorPath( assertThat(unauthenticatedResponse.statusCode()).isEqualTo(401); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String accountUuid = "f22f310d-5464-45f0-9dc4-c37353004403"; + String token = jwtUtil.generateToken(accountUuid, Map.of("accountId", accountUuid)); HttpRequest authenticatedRequest = externalLinkRequest(route, token); HttpResponse authenticatedResponse = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/GrpcJwtAuthInterceptorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/GrpcJwtAuthInterceptorTest.java index cdad776a8c..4a307e5083 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/GrpcJwtAuthInterceptorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/GrpcJwtAuthInterceptorTest.java @@ -36,7 +36,10 @@ void rejectsMissingToken() { @Test void allowsValidToken() { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String accountUuid = "f22f310d-5464-45f0-9dc4-c37353004403"; + String token = + jwtUtil.generateToken( + accountUuid, Map.of("accountId", accountUuid, "globalRoles", List.of("platformAdmin"))); TestServerCall call = new TestServerCall(); Metadata headers = new Metadata(); headers.put( 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 28985b7222..2e0f68bd1c 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 @@ -686,6 +686,55 @@ void authenticateConvertsIllegalStateToBoundedAuthorityUnavailableError() { 1.0, registry.get("grpc.app_error").tag("code", "AUTH_UNAVAILABLE").counter().count()); } + @Test + void authenticatePreservesAccountOwnerUnavailableAsApplicationError() { + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.authenticateForGameplay("demo@example.com", "password")) + .thenThrow( + new AuthenticationException("AUTH_UNAVAILABLE", "Account authority is unavailable")); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), accountService); + RecordingObserver observer = new RecordingObserver<>(); + + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + observer); + + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals("Account authority is unavailable", observer.response().getError().getMessage()); + assertTrue(observer.response().getAuthToken().isEmpty()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + } + + @Test + void verifyEmailLoginOtpPreservesAccountOwnerUnavailableAsApplicationError() { + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.verifyEmailLoginOtp("demo@example.com", "123456")) + .thenThrow( + new AuthenticationException("AUTH_UNAVAILABLE", "Account authority is unavailable")); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), accountService); + RecordingObserver observer = new RecordingObserver<>(); + + service.verifyEmailLoginOtp( + VerifyEmailLoginOtpRequest.newBuilder() + .setEmail("demo@example.com") + .setCode("123456") + .build(), + observer); + + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals( + "Account authority unavailable; retry later", observer.response().getError().getMessage()); + assertTrue(observer.response().getAuthToken().isEmpty()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + } + @Test void requestEmailLoginOtpDispatchesNeutralChallengeRequest() { 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 314bc88f0b..1710c17e23 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 @@ -144,6 +144,7 @@ class AccountServiceImplTest { passwordResetTokenRepository; private AccountServiceImpl service; + private JwtUtil jwtUtil; @BeforeEach void setup() { @@ -164,7 +165,7 @@ void setup() { when(subscriptionRepository.findByTenantId(8L)) .thenReturn(java.util.List.of(explicitActiveEntitlementForSecondTenant)); AccountMapper mapper = Mappers.getMapper(AccountMapper.class); - JwtUtil jwtUtil = new ReloadableJwtUtil(JWT_SECRET, 3600000L); + jwtUtil = org.mockito.Mockito.spy(new ReloadableJwtUtil(JWT_SECRET, 3600000L)); jwtAuthProperties.setJwtSecret(JWT_SECRET); tokenProperties.setPlayerBootstrapExpirationMs(300000L); tokenProperties.setConnectScopeExpirationMs(120000L); @@ -253,6 +254,178 @@ void setup() { transactionManager); } + private enum OrdinaryIssuance { + CONTROL_UI, + GAMEPLAY_PASSWORD, + EMAIL_OTP, + PLAYER_BOOTSTRAP + } + + private enum IdentityFailure { + MISSING_UUID, + NIL_UUID, + MISSING_PROVENANCE, + MISSING_SOURCE_ROW, + WRONG_SOURCE_ROW, + MISSING_LOOKUP, + DIFFERENT_LOOKUP_OWNER, + DIFFERENT_LOOKUP_UUID, + READBACK_UNAVAILABLE + } + + private static java.util.stream.Stream + ordinaryIssuanceIdentityFailures() { + return java.util.Arrays.stream(OrdinaryIssuance.values()) + .flatMap( + mode -> + java.util.Arrays.stream(IdentityFailure.values()) + .map(failure -> org.junit.jupiter.params.provider.Arguments.of(mode, failure))); + } + + @ParameterizedTest + @org.junit.jupiter.params.provider.MethodSource("ordinaryIssuanceIdentityFailures") + void ordinaryIssuanceRejectsUnverifiedOwnerBeforeSigningOrConsumingChallenge( + OrdinaryIssuance mode, IdentityFailure failure) { + Account account = ordinaryIssuanceAccount(); + var challenge = ordinaryIssuanceChallenge(account); + switch (failure) { + case MISSING_UUID -> account.setAccountUuid(null); + case NIL_UUID -> account.setAccountUuid(new UUID(0L, 0L)); + case MISSING_PROVENANCE -> account.setAccountUuidProvenance(null); + case MISSING_SOURCE_ROW -> account.setAccountUuidSourceNumericId(null); + case WRONG_SOURCE_ROW -> account.setAccountUuidSourceNumericId(43L); + case MISSING_LOOKUP -> + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenReturn(Optional.empty()); + case DIFFERENT_LOOKUP_OWNER, DIFFERENT_LOOKUP_UUID -> { + Account different = new Account(); + different.setId(failure == IdentityFailure.DIFFERENT_LOOKUP_OWNER ? 43L : 42L); + different.setAccountUuid( + failure == IdentityFailure.DIFFERENT_LOOKUP_UUID + ? UUID.randomUUID() + : account.getAccountUuid()); + different.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + different.setAccountUuidSourceNumericId(different.getId()); + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenReturn(Optional.of(different)); + } + case READBACK_UNAVAILABLE -> + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenThrow( + new org.springframework.dao.DataAccessResourceFailureException( + "private storage detail")); + } + + AuthenticationException denied = + assertThrows(AuthenticationException.class, () -> issueOrdinaryCredential(mode)); + + assertEquals("AUTH_UNAVAILABLE", denied.getCode()); + assertEquals("Account authority is unavailable", denied.getMessage()); + org.mockito.Mockito.verify(jwtUtil, org.mockito.Mockito.never()) + .generateToken( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyMap()); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(challenge); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(sessionService); + } + + @ParameterizedTest + @EnumSource(OrdinaryIssuance.class) + void ordinaryIssuanceKeepsItsProfileContractAfterExactOwnerReadback(OrdinaryIssuance mode) { + Account account = ordinaryIssuanceAccount(); + var challenge = ordinaryIssuanceChallenge(account); + + String token = issueOrdinaryCredential(mode); + + var claims = jwtUtil.parseToken(token).getPayload(); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + org.mockito.Mockito.verify(accountRepository).findByAccountUuid(account.getAccountUuid()); + if (mode != OrdinaryIssuance.GAMEPLAY_PASSWORD) { + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).delete(challenge); + } + org.mockito.Mockito.verify(sessionService) + .storeAccountSession( + org.mockito.ArgumentMatchers.eq(42L), + org.mockito.ArgumentMatchers.eq(token), + org.mockito.ArgumentMatchers.anyLong()); + } + + @ParameterizedTest + @EnumSource(OrdinaryIssuance.class) + void invalidCredentialsDoNotConsultUuidOwnerReadback(OrdinaryIssuance mode) { + Account account = ordinaryIssuanceAccount(); + ordinaryIssuanceChallenge(account); + account.setAccountUuid(null); + + AuthenticationException denied = + assertThrows( + AuthenticationException.class, + () -> { + switch (mode) { + case CONTROL_UI -> service.authenticate("owner@example.com", "wrong"); + case GAMEPLAY_PASSWORD -> + service.authenticateForGameplay("owner@example.com", "wrong"); + case EMAIL_OTP -> service.verifyEmailLoginOtp("owner@example.com", "wrong"); + case PLAYER_BOOTSTRAP -> service.issuePlayerBootstrap("owner@example.com", "wrong"); + } + }); + + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, denied.getCode()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .findByAccountUuid(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(sessionService); + } + + private Account ordinaryIssuanceAccount() { + Account account = new Account(); + account.setId(42L); + account.setUsername("owner"); + account.setEmail("owner@example.com"); + account.setEmailVerified(true); + account.setLoginAuthModes("PASSWORD,EMAIL_OTP"); + account.setPasswordHash(hash("password")); + setPersistedAuthenticationIdentity(account); + when(accountRepository.findByEmail("owner@example.com")).thenReturn(Optional.of(account)); + return account; + } + + private net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge + ordinaryIssuanceChallenge(Account account) { + var challenge = new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(3L); + challenge.setAccountId(account.getId()); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountEmailLoginChallengeRepository.findByAccountId(account.getId())) + .thenReturn(Optional.of(challenge)); + return challenge; + } + + private String issueOrdinaryCredential(OrdinaryIssuance mode) { + if (mode == OrdinaryIssuance.PLAYER_BOOTSTRAP) { + PlayerBootstrapResult result = service.issuePlayerBootstrap("owner@example.com", "123456"); + assertNotNull( + net.firedevops.firemud.accountservice.AccountUuidText.parseOrNull(result.accountId())); + return result.bootstrapToken(); + } + AuthenticationResult result = + switch (mode) { + case CONTROL_UI -> service.authenticate("owner@example.com", "123456"); + case GAMEPLAY_PASSWORD -> + service.authenticateForGameplay("owner@example.com", "password"); + case EMAIL_OTP -> service.verifyEmailLoginOtp("owner@example.com", "123456"); + case PLAYER_BOOTSTRAP -> throw new IllegalStateException("Bootstrap handled above"); + }; + assertEquals( + jwtUtil.parseToken(result.authToken()).getPayload().getSubject(), result.accountId()); + return result.authToken(); + } + @ParameterizedTest @EnumSource(AccountIdentityProvenance.class) void resolvesAccountUuidToPrivateStorageIdForEachSupportedProvenance( @@ -2022,9 +2195,11 @@ void gameplayAuthenticationRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( when(accountEmailLoginChallengeRepository.findByAccountId(32L)) .thenReturn(Optional.of(challenge)); - assertThrows( - IllegalStateException.class, - () -> service.authenticateForGameplay("unproved@example.com", "123456")); + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> service.authenticateForGameplay("unproved@example.com", "123456")); + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(32L); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(32L); @@ -2204,7 +2379,10 @@ void issuePlayerBootstrapRejectsUnprovedIdentityBeforeConsumingOtpOrMinting( when(accountEmailLoginChallengeRepository.findByAccountId(50L)) .thenReturn(Optional.of(challenge)); - assertThrows(IllegalStateException.class, () -> service.issuePlayerBootstrap("demo", "123456")); + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, () -> service.issuePlayerBootstrap("demo", "123456")); + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(50L); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(50L); @@ -2260,6 +2438,96 @@ void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { .storeAccountSession(7L, result.bootstrapToken(), 300000L); } + private static java.util.stream.Stream + invalidBootstrapAccountClaims() { + String valid = "10000000-0000-4000-8000-00000000000a"; + return java.util.stream.Stream.of( + org.junit.jupiter.params.provider.Arguments.of("11", "11"), + org.junit.jupiter.params.provider.Arguments.of((String) null, valid), + org.junit.jupiter.params.provider.Arguments.of( + valid.toUpperCase(java.util.Locale.ROOT), valid), + org.junit.jupiter.params.provider.Arguments.of(" " + valid, valid), + org.junit.jupiter.params.provider.Arguments.of(valid, (Object) null), + org.junit.jupiter.params.provider.Arguments.of(valid, ""), + org.junit.jupiter.params.provider.Arguments.of(valid, 11L), + org.junit.jupiter.params.provider.Arguments.of(valid, "11"), + org.junit.jupiter.params.provider.Arguments.of( + valid, "00000000-0000-0000-0000-000000000000"), + org.junit.jupiter.params.provider.Arguments.of( + "00000000-0000-0000-0000-000000000000", valid), + org.junit.jupiter.params.provider.Arguments.of(valid, "not-a-uuid"), + org.junit.jupiter.params.provider.Arguments.of( + valid, valid.toUpperCase(java.util.Locale.ROOT)), + org.junit.jupiter.params.provider.Arguments.of(valid, " " + valid), + org.junit.jupiter.params.provider.Arguments.of( + valid, "10000000-0000-4000-8000-000000000002")); + } + + @ParameterizedTest + @org.junit.jupiter.params.provider.MethodSource("invalidBootstrapAccountClaims") + void bootstrapReaderRejectsNonUuidOrContradictoryIdentityBeforeOwnerOrSessionUse( + String subject, Object accountClaim) { + Map claims = new java.util.HashMap<>(); + claims.put("aud", "player-bootstrap"); + if (accountClaim != null) { + claims.put("accountId", accountClaim); + } + String token = new JwtUtil(JWT_SECRET, 300000L).generateToken(subject, claims); + + AuthenticationException denied = + assertThrows(AuthenticationException.class, () -> service.listBootstrapWorlds(token)); + + assertEquals("CONNECT_CONTEXT_INVALID", denied.getCode()); + verifyNoInteractions(accountRepository, sessionService); + } + + @ParameterizedTest + @ValueSource(strings = {"missing", "wrong-owner-uuid", "unavailable"}) + void bootstrapReaderReportsOwnerReadbackFailureBeforeSessionUse(String failure) { + UUID uuid = UUID.fromString("10000000-0000-4000-8000-000000000001"); + if (failure.equals("unavailable")) { + when(accountRepository.findByAccountUuid(uuid)) + .thenThrow( + new org.springframework.dao.DataAccessResourceFailureException("private detail")); + } else if (failure.equals("wrong-owner-uuid")) { + Account owner = new Account(); + owner.setId(11L); + owner.setAccountUuid(UUID.randomUUID()); + owner.setAccountUuidSourceNumericId(11L); + owner.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + when(accountRepository.findByAccountUuid(uuid)).thenReturn(Optional.of(owner)); + } + String token = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken( + uuid.toString(), Map.of("aud", "player-bootstrap", "accountId", uuid.toString())); + + AuthenticationException denied = + assertThrows(AuthenticationException.class, () -> service.listBootstrapWorlds(token)); + + assertEquals("AUTH_UNAVAILABLE", denied.getCode()); + assertEquals("Account authority is unavailable", denied.getMessage()); + verifyNoInteractions(sessionService); + } + + @Test + void bootstrapReaderResolvesUuidBeforeReadingPrivateAccountSession() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + String uuid = account.getAccountUuid().toString(); + String token = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken(uuid, Map.of("aud", "player-bootstrap", "accountId", uuid)); + when(sessionService.isAccountSessionActive(11L, token)).thenReturn(true); + + assertFalse(service.listBootstrapWorlds(token).isEmpty()); + + org.mockito.InOrder reads = org.mockito.Mockito.inOrder(accountRepository, sessionService); + reads.verify(accountRepository).findByAccountUuid(account.getAccountUuid()); + reads.verify(sessionService).isAccountSessionActive(11L, token); + } + @Test void listBootstrapWorldsRejectsInactiveAccountBootstrapToken() { Account account = new Account(); @@ -3356,6 +3624,82 @@ void issueDirectTextConnectScopeRetainsScopeForActiveEntitlement() { .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); } + @Test + void bothScopeProducersBindPersistedUuidWhileRetainedRowsKeepPrivateAccountKey() { + Account account = directTextAccount(); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String browser = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + String direct = + service + .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) + .connectScopeId(); + for (String token : java.util.List.of(browser, direct)) { + var claims = jwtUtil.parseToken(token).getPayload(); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + AuthenticationException held = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), new ConnectTokenRequest(token, "held-proof"))); + assertEquals("AUTH_UNAVAILABLE", held.getCode()); + } + var retained = org.mockito.ArgumentCaptor.forClass(VerifiedJoinScope.class); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.times(2)) + .insert(retained.capture()); + for (VerifiedJoinScope row : retained.getAllValues()) { + assertEquals(11L, row.accountId()); + assertEquals( + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.scope(row), + row.snapshotDigest()); + } + } + + @Test + void scopeReaderOwnerFailureIsUnavailableAndNumericScopesNeverReachOwnerLookup() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + String scope = + service + .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) + .connectScopeId(); + var decoded = new java.util.HashMap(jwtUtil.parseToken(scope).getPayload()); + decoded.remove("iat"); + decoded.remove("exp"); + decoded.put("sub", "11"); + decoded.put("accountId", "11"); + String numeric = new JwtUtil(JWT_SECRET, 120000L).generateToken("11", decoded); + org.mockito.Mockito.clearInvocations(accountRepository); + AuthenticationException invalid = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProductionFromGameSession( + directTextCaller(), + new JoinPublicProductionRequest(numeric, directTextCaller().requestId()))); + assertEquals("CONNECT_SCOPE_INVALID", invalid.getCode()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .findByAccountUuid(org.mockito.ArgumentMatchers.any()); + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenThrow( + new org.springframework.dao.DataAccessResourceFailureException("private detail")); + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProductionFromGameSession( + directTextCaller(), + new JoinPublicProductionRequest(scope, directTextCaller().requestId()))); + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + } + @Test void getTenantEntitlementsForRuntimeTreatsStoreFailureAsUnavailable() { DataAccessResourceFailureException cause = @@ -4030,7 +4374,8 @@ void listBootstrapRealmsReadsFreshEntitlementsAndReusesVerifiedAccountIdentity() assertEquals(2, secondCall.size()); org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) .findByTenantId(7L); - org.mockito.Mockito.verify(accountRepository).findByAccountUuid(account.getAccountUuid()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.times(1 + secondCall.size())) + .findByAccountUuid(account.getAccountUuid()); org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()).findById(11L); JwtUtil tokenReader = new JwtUtil(JWT_SECRET, 3600000L); for (var realm : secondCall) { diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java index 0a9b3fefdd..9407390682 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java @@ -52,7 +52,7 @@ public static String requireCanonicalAccountUuid(Object value, String claimName) } public static String requireSignedGameplayAccountUuid(Claims claims, String mismatchMessage) { - String subjectAccountUuid = requireCanonicalAccountUuid(claims.getSubject(), "sub"); + String subjectAccountUuid = requireCanonicalAccountUuid(claims.get("sub"), "sub"); String claimedAccountUuid = requireCanonicalAccountUuid(claims.get("accountId"), "accountId"); if (!subjectAccountUuid.equals(claimedAccountUuid)) { throw new IllegalArgumentException(mismatchMessage); diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtClaimsTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtClaimsTest.java index 7b81647534..dcf37f99d9 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtClaimsTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/JwtClaimsTest.java @@ -211,4 +211,39 @@ void requireSignedGameplayAccountUuidRejectsNoncanonicalOrIncompatibleCarriers() IllegalArgumentException.class, () -> JwtClaims.requireSignedGameplayAccountUuid(numericClaim, "account subject mismatch")); } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource( + strings = { + "11", + "", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "10000000-0000-4000-8000-00000000000A", + " 10000000-0000-4000-8000-00000000000a " + }) + void routingScopeRejectsNoncanonicalAccountIdentity(String value) { + var claims = io.jsonwebtoken.Jwts.claims().add("sub", value).add("accountId", value).build(); + assertThrows( + IllegalArgumentException.class, + () -> JwtClaims.requireSignedGameplayRoutingClaims(claims, "mismatch")); + } + + @Test + void routingScopeRejectsNumericObjectsAndDifferentUuidSubjects() { + Claims numeric = org.mockito.Mockito.mock(Claims.class); + org.mockito.Mockito.when(numeric.get("sub")).thenReturn(11L); + org.mockito.Mockito.when(numeric.get("accountId")).thenReturn(11L); + for (var claims : + java.util.List.of( + numeric, + io.jsonwebtoken.Jwts.claims() + .add("sub", "10000000-0000-4000-8000-000000000001") + .add("accountId", "10000000-0000-4000-8000-000000000002") + .build())) { + assertThrows( + IllegalArgumentException.class, + () -> JwtClaims.requireSignedGameplayRoutingClaims(claims, "mismatch")); + } + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java index f982374d18..1c0dd55172 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java @@ -64,6 +64,20 @@ public CommunicationCommandHandlingResult handle( meterRegistry.counter(COMMUNICATION_INVOCATIONS_METRIC, "type", typeTag).increment(); meterRegistry.counter(metricPrefix(command.type()) + ".invocations").increment(); + if (!SessionContext.isCanonicalAccountIdentity(context.accountId())) { + logFailure( + "INVALID_ARGUMENT", + "Sender Account identity unavailable", + context, + tenantTag, + command.type(), + null); + return new CommunicationCommandHandlingResult( + CommandEnqueueResult.failure( + "COMMUNICATION_NOT_DELIVERED", "Sender Account identity unavailable"), + List.of()); + } + ParsedCommunication parsed; try { parsed = parseCommunication(context, command); 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 0da784abf2..593a11476e 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 @@ -105,6 +105,7 @@ void websocketSayFlowReportsCanonicalTranscriptAndMetrics() throws Exception { assertThat(socialStub().lastRequest()) .hasValueSatisfying( request -> { + assertThat(request.getSenderId()).isEqualTo(ACCOUNT_UUID); assertThat(request.getContent()).isEqualTo("hello travelers"); assertThat(request.getType()) .isEqualTo(net.firedevops.firemud.socialgroups.v1.ChatType.CHAT_TYPE_SAY); @@ -155,6 +156,8 @@ void websocketWhisperFlowReportsCanonicalTranscriptAndMetadata() throws Exceptio ChatTestFixtures.PLAYER_SORA, "keep quiet", true); + assertThat(socialStub().lastRequest()) + .hasValueSatisfying(request -> assertThat(request.getSenderId()).isEqualTo(ACCOUNT_UUID)); GameplayAsyncAssertions.assertMetricEventually( gameSession().bean(io.micrometer.core.instrument.MeterRegistry.class), @@ -181,6 +184,8 @@ void websocketTellFlowReportsCanonicalTranscriptAndMetadata() throws Exception { ChatTestFixtures.PLAYER_SORA, "meet me at the forge", true); + assertThat(socialStub().lastRequest()) + .hasValueSatisfying(request -> assertThat(request.getSenderId()).isEqualTo(ACCOUNT_UUID)); GameplayAsyncAssertions.assertMetricEventually( gameSession().bean(io.micrometer.core.instrument.MeterRegistry.class), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java index 2eec93f6c6..4f1692b034 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java @@ -28,6 +28,9 @@ import org.mockito.Mockito; class CommunicationCommandHandlerTest { + private static final String CALLER_ACCOUNT_UUID = "11111111-1111-4111-8111-111111111111"; + private static final String TARGET_ACCOUNT_UUID = "22222222-2222-4222-8222-222222222222"; + private final EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); private final GameLogicClient gameLogicClient = Mockito.mock(GameLogicClient.class); @@ -44,7 +47,7 @@ class CommunicationCommandHandlerTest { new SessionContext( 1L, 22L, - "123", + CALLER_ACCOUNT_UUID, "emberline@example.com", 911L, "Emberline", @@ -125,6 +128,38 @@ void saySuccessReturnsCanonicalText() { && gameplayCommand.getCommandId().startsWith("comm-"))); } + @Test + void communicationRejectsMissingOrMalformedAccountIdentityBeforeLookingUpOrPublishing() { + for (String accountId : + new String[] { + null, + "123", + "11111111-1111-4111-8111-11111111111A", + "00000000-0000-0000-0000-000000000000" + }) { + CommunicationCommandHandlingResult result = + handler.handle( + sessionContextWithAccountId(accountId), + new TextCommand( + TextCommandType.TELL, + List.of("Sora", "Meet me later"), + "TELL Sora Meet me later")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("COMMUNICATION_NOT_DELIVERED"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("Sender Account identity unavailable"); + assertThat(result.outputs()).isEmpty(); + } + + Mockito.verifyNoInteractions( + entityManagementClient, + gameLogicClient, + sessionAuthenticationService, + recipientDeliveryService, + scriptEventPublisher); + } + @Test void whisperRequiresTargetAndMessage() { CommunicationCommandHandlingResult result = @@ -145,7 +180,7 @@ void tellRequiresOnlineTarget() { Character.newBuilder() .setId("300") .setTenantId("22") - .setAccountId("700") + .setAccountId(TARGET_ACCOUNT_UUID) .setName("Sora") .build())); when(sessionAuthenticationService.resolveByGameplayName(22L, 1L, "Sora")) @@ -165,7 +200,17 @@ void tellRequiresOnlineTarget() { void tellFailsClosedWhenTargetGameplayBindingNormalizesAway() { SessionContext normalizedTarget = new SessionContext( - 77L, 22L, "700", "sora@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 77L, + 22L, + TARGET_ACCOUNT_UUID, + "sora@example.com", + 0L, + null, + 0L, + null, + "jwt", + "en-NZ", + 1L); when(entityManagementClient.findCharacterByName( sessionContext, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "Sora")) .thenReturn( @@ -173,7 +218,7 @@ void tellFailsClosedWhenTargetGameplayBindingNormalizesAway() { Character.newBuilder() .setId("300") .setTenantId("22") - .setAccountId("700") + .setAccountId(TARGET_ACCOUNT_UUID) .setName("Sora") .build())); when(sessionAuthenticationService.resolveByGameplayName(22L, 1L, "Sora")) @@ -209,7 +254,7 @@ void tellReturnsUnavailableWithoutPublishingOrCallingGameLogicWhenTargetSessionI Character.newBuilder() .setId("300") .setTenantId("22") - .setAccountId("700") + .setAccountId(TARGET_ACCOUNT_UUID) .setName("Sora") .build())); when(sessionAuthenticationService.resolveByGameplayName(22L, 1L, "Sora")) @@ -349,4 +394,23 @@ private static String joinedOutputText(List outputs) { .reduce((left, right) -> left + "\n" + right) .orElse(null); } + + private SessionContext sessionContextWithAccountId(String accountId) { + return new SessionContext( + sessionContext.sessionId(), + sessionContext.tenantId(), + accountId, + sessionContext.loginName(), + sessionContext.characterId(), + sessionContext.characterName(), + sessionContext.gameInstanceId(), + sessionContext.roomInstanceId(), + sessionContext.jwt(), + sessionContext.localeTag(), + sessionContext.bootstrapGameInstanceId(), + sessionContext.worldSlug(), + sessionContext.realmSlug(), + sessionContext.pointerVersion(), + sessionContext.playableStateScope()); + } } 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 071bcf71f9..8a5037e9dd 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 @@ -1336,7 +1336,7 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(false).build()); + .thenReturn(realmGrantResponse(false)); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1362,7 +1362,7 @@ void playInvisibleRealmWithDeniedGrantClearsBinding() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(false).build()); + .thenReturn(realmGrantResponse(false)); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1465,44 +1465,6 @@ void playGrantedRealmWithoutGrantGenerationFailsUnavailable() { verifyNoGameplayBindingSideEffects(); } - @Test - void playMismatchedRealmGrantCorrelationFailsUnavailable() { - SessionContext context = previewRealmContext(); - when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString())) - .thenReturn(realmGrantResponse(true).toBuilder().setRealmSlug("other-realm").build()); - - PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); - - assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); - verifyNoGameplayBindingSideEffects(); - } - - @Test - void playGrantedRealmWithoutGrantGenerationFailsUnavailable() { - SessionContext context = previewRealmContext(); - when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString())) - .thenReturn(realmGrantResponse(true).toBuilder().setGrantVersion(0L).build()); - - PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); - - assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); - verifyNoGameplayBindingSideEffects(); - } - @ParameterizedTest @ValueSource(strings = {"NOT_FOUND", "PERMISSION_DENIED"}) void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String errorCode) { @@ -1593,45 +1555,7 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { @ParameterizedTest @ValueSource( strings = { - ACCOUNT_ID, - "not-a-uuid", - "00000000-0000-0000-0000-000000000000", - "5E1340F8-99C8-49FA-A4FE-5FC9D2075621", - " 5e1340f8-99c8-49fa-a4fe-5fc9d2075621" - }) - void playWhenMembershipAuthorityAccountDoesNotExactlyMatchFailsClosed(String responseAccountId) { - SessionContext context = - new SessionContext( - 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); - when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId(responseAccountId) - .setTenantId("22") - .setMembershipExists(true) - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); - - PlayCommandHandlingResult result = - handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); - - assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); - Mockito.verify(gameplayPresenceLifecycleService, never()) - .clearGameplayBinding(Mockito.any(), Mockito.anyString()); - Mockito.verify(sessionContextService, never()).save(Mockito.any()); - Mockito.verify(moderationPolicyClient, never()) - .evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString()); - } - - @ParameterizedTest - @ValueSource( - strings = { + "c04bf730-5f95-4357-a850-ac29eca1754e", "123", "not-a-uuid", "00000000-0000-0000-0000-000000000000", @@ -1997,23 +1921,6 @@ private static GetRealmAccessGrantForRuntimeResponse realmGrantResponse( .build(); } - private static GetRealmAccessGrantForRuntimeResponse realmGrantResponse(boolean granted) { - return realmGrantResponse(ACCOUNT_ID, "22", "sandbox", "preview", granted); - } - - private static GetRealmAccessGrantForRuntimeResponse realmGrantResponse( - String accountId, String tenantId, String worldSlug, String realmSlug, boolean granted) { - return GetRealmAccessGrantForRuntimeResponse.newBuilder() - .setAccountId(accountId) - .setTenantId(tenantId) - .setWorldSlug(worldSlug) - .setRealmSlug(realmSlug) - .setGranted(granted) - .setGrantVersion(granted ? 3L : 0L) - .setEvaluatedAt(Instant.now().toString()) - .build(); - } - private static GameplayCatalogProperties.World world( String slug, String displayName, List realms) { GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); 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 b12053c53d..cfc54dac80 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 @@ -49,7 +49,6 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.IpConnectionLimiter; import net.firedevops.firemud.gamesession.service.PingService; -import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.TickService; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionRequest; 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 806894b71b..3a385a8ad2 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 @@ -21,6 +21,20 @@ public boolean hasAccountAccess(long tenantId, String accountId) { return isCurrentAccount(accountId); } + /** Allows tenant-authorized guild ownership or exact self-ownership for an ordinary caller. */ + public boolean hasGuildOwnerAccess(long tenantId, String accountId) { + if (tenantId <= 0) { + return false; + } + try { + String canonicalAccountId = + JwtClaims.requireCanonicalAccountUuid(accountId, "ownerAccountId"); + return SessionContext.hasTenantAccess(tenantId) || isCurrentAccount(canonicalAccountId); + } catch (IllegalArgumentException ex) { + return false; + } + } + public void requireTenantAccess(long tenantId) { SessionContext.requireTenantAccess(tenantId); } 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 4fd4562772..a1ce27184c 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 @@ -4,7 +4,6 @@ import java.time.Instant; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.common.LoggingUtil; -import net.firedevops.firemud.socialgroups.client.LoggingAdminClient; import net.firedevops.firemud.socialgroups.dto.AddGuildMemberRequest; import net.firedevops.firemud.socialgroups.dto.AddGuildStorageItemRequest; import net.firedevops.firemud.socialgroups.dto.CreateAllianceRequest; @@ -47,8 +46,6 @@ public class GuildServiceImpl implements GuildService { private final GuildMemberRepository guildMemberRepository; private final GuildMemberMapper guildMemberMapper; - private final LoggingAdminClient loggingAdminClient; - @Override @Transactional @Timed(value = "guild.create") @@ -62,8 +59,8 @@ public GuildDto createGuild(CreateGuildRequest request) { Guild saved = guildRepository.save(guild); runAfterCommit( () -> - safeReportModeration( - request.tenantId(), request.ownerAccountId(), "Guild created: " + request.name())); + logLifecycle( + request.tenantId(), saved.getId(), request.ownerAccountId(), "CREATE", null)); return guildMapper.toDto(saved); } @@ -107,8 +104,12 @@ public GuildMemberDto addMember(AddGuildMemberRequest request) { member.setId(saved.getId()); runAfterCommit( () -> - safeReportModeration( - request.tenantId(), request.accountId(), "Joined guild " + request.guildId())); + logLifecycle( + request.tenantId(), + request.guildId(), + request.accountId(), + "ADD_MEMBER", + request.role())); return guildMemberMapper.toDto(member); } @@ -130,10 +131,12 @@ public GuildMemberDto updateMemberRole(UpdateGuildMemberRoleRequest request) { guildMemberRepository.save(member); runAfterCommit( () -> - safeReportModeration( + logLifecycle( request.tenantId(), + request.guildId(), request.accountId(), - "Updated guild role to " + request.role())); + "UPDATE_MEMBER_ROLE", + request.role())); return guildMemberMapper.toDto(member); } @@ -150,18 +153,22 @@ public void removeMember(long tenantId, long guildId, String accountId) { return; } guildMemberRepository.delete(member); - runAfterCommit(() -> safeReportModeration(tenantId, accountId, "Left guild " + guildId)); + runAfterCommit( + () -> logLifecycle(tenantId, guildId, accountId, "REMOVE_MEMBER", member.getRole())); } - private void safeReportModeration(long tenantId, String accountId, String description) { + private void logLifecycle( + long tenantId, Long guildId, String accountId, String action, String role) { try { - loggingAdminClient.reportChatViolation(tenantId, accountId, description); - } catch (RuntimeException ex) { - logger.warn( - "Failed to report guild moderation event for tenant {} account {}", + logger.info( + "Guild lifecycle committed tenant={} guild={} account={} action={} role={}", tenantId, + guildId, accountId, - ex); + action, + role); + } catch (RuntimeException ex) { + // Operational logging must not turn an already committed mutation into an API failure. } } 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 801552b84a..71ea0d38b4 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 @@ -161,7 +161,8 @@ public void createGuild( StreamObserver responseObserver) { try { AccountScope ownerScope = - requireAccountScope(request.getTenantId(), request.getOwnerAccountId(), "ownerAccountId"); + requireGuildOwnerScope( + request.getTenantId(), request.getOwnerAccountId(), "ownerAccountId"); CreateGuildRequest dto = new CreateGuildRequest(ownerScope.tenantId(), ownerScope.accountId(), request.getName()); var guild = guildService.createGuild(dto); @@ -867,8 +868,18 @@ private AccountScope requireAccountScope( return new AccountScope(tenantId, accountId); } + private AccountScope requireGuildOwnerScope( + String tenantIdText, String accountIdText, String accountFieldName) { + long tenantId = RequestIdValidation.requirePositiveLong(tenantIdText, "tenantId"); + String accountId = JwtClaims.requireCanonicalAccountUuid(accountIdText, accountFieldName); + if (!socialAccessGuard.hasGuildOwnerAccess(tenantId, accountId)) { + throw new AuthorizationException("Guild owner access required"); + } + return new AccountScope(tenantId, accountId); + } + private String optionalAccountUuid(String value, String fieldName) { - return value == null || value.isEmpty() + return value == null || value.isBlank() ? null : JwtClaims.requireCanonicalAccountUuid(value, fieldName); } 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 2762c4d3f5..aa9935f222 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 @@ -58,7 +58,12 @@ void createGuildAllowsScopedTenantAdmin() throws Exception { CreateGuildRequest request = new CreateGuildRequest(1L, accountUuid(2L), "guild"); when(guildService.createGuild(request)) .thenReturn(new GuildDto(1L, 1L, "guild", accountUuid(2L), Instant.now())); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + accountUuid(2L), + Map.of( + "accountId", accountUuid(2L), + "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -75,7 +80,11 @@ void createGuildAllowsScopedTenantAdmin() throws Exception { void createGuildRejectsCrossTenantScopedAdmin() throws Exception { CreateGuildRequest request = new CreateGuildRequest(1L, accountUuid(2L), "guild"); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + jwtUtil.generateToken( + accountUuid(2L), + Map.of( + "accountId", accountUuid(2L), + "scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -89,7 +98,12 @@ void createGuildRejectsCrossTenantScopedAdmin() throws Exception { @Test void createGuildRejectsZeroTenantIdBeforeDispatch() throws Exception { CreateGuildRequest request = new CreateGuildRequest(0L, accountUuid(2L), "guild"); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + accountUuid(2L), + Map.of( + "accountId", accountUuid(2L), + "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -108,7 +122,12 @@ void createGuildRejectsZeroTenantIdBeforeDispatch() throws Exception { @Test void addMemberRejectsZeroGuildIdBeforeDispatch() throws Exception { AddGuildMemberRequest request = new AddGuildMemberRequest(1L, 0L, accountUuid(2L), "member"); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + accountUuid(2L), + Map.of( + "accountId", accountUuid(2L), + "globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/PingControllerTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/PingControllerTest.java index 266b936cb8..f5d5e80e6d 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/PingControllerTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/PingControllerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.socialgroups.controller; +import static net.firedevops.firemud.socialgroups.test.AccountUuidFixtures.accountUuid; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @@ -34,7 +35,12 @@ class PingControllerTest { void pingEndpointReturnsPong() throws Exception { when(pingService.ping()).thenReturn("pong"); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + accountUuid(2L), + Map.of( + "accountId", accountUuid(2L), + "globalRoles", List.of("platformAdmin"))); mockMvc .perform(get("/ping").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) 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 4ba2a87638..09b32a3cf9 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 @@ -78,7 +78,7 @@ void createTokenRejectsZeroAccountIdBeforeAccessCheckAndDispatch() throws Except .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.status").value("ERROR")) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("Malformed claim: accountId")); + .andExpect(jsonPath("$.error.message").value("Request body is malformed")); verifyNoInteractions(service, socialAccessGuard); } 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 de37e761dd..5654a48c06 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 @@ -57,4 +57,28 @@ void hasAccountAccessRejectsMalformedRequestedAccountAndAbsentCaller() { assertFalse(guard.hasAccountAccess(1L, "42")); assertFalse(guard.hasAccountAccess(0L, accountUuid(42L))); } + + @Test + void hasGuildOwnerAccessAcceptsMatchingOrdinaryAccountUuidWithoutTenantRole() { + SessionContext.setContext(accountUuid(42L), List.of(), Map.of()); + + assertTrue(guard.hasGuildOwnerAccess(1L, accountUuid(42L))); + } + + @Test + void hasGuildOwnerAccessRetainsTenantPrivilegeForAnotherCanonicalOwner() { + SessionContext.setContext(accountUuid(42L), List.of(), Map.of("1", List.of("tenantAdmin"))); + + assertTrue(guard.hasGuildOwnerAccess(1L, accountUuid(43L))); + assertFalse(guard.hasGuildOwnerAccess(2L, accountUuid(43L))); + } + + @Test + void hasGuildOwnerAccessRejectsOtherOwnerWithoutTenantPrivilege() { + SessionContext.setContext(accountUuid(42L), List.of(), Map.of()); + + assertFalse(guard.hasGuildOwnerAccess(1L, accountUuid(43L))); + assertFalse(guard.hasGuildOwnerAccess(0L, accountUuid(42L))); + assertFalse(guard.hasGuildOwnerAccess(1L, "42")); + } } 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 26965977b5..073535f20b 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 @@ -7,65 +7,57 @@ import static org.mockito.Mockito.when; import net.firedevops.firemud.socialgroups.dto.AddGuildMemberRequest; +import net.firedevops.firemud.socialgroups.dto.CreateGuildRequest; import net.firedevops.firemud.socialgroups.dto.GuildMemberDto; import net.firedevops.firemud.socialgroups.dto.UpdateGuildMemberRoleRequest; +import net.firedevops.firemud.socialgroups.entity.Guild; import net.firedevops.firemud.socialgroups.entity.GuildMember; +import net.firedevops.firemud.socialgroups.mapper.GuildMapper; import net.firedevops.firemud.socialgroups.mapper.GuildMemberMapper; import net.firedevops.firemud.socialgroups.repository.GuildMemberRepository; +import net.firedevops.firemud.socialgroups.repository.GuildRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mapstruct.factory.Mappers; import org.mockito.Mockito; class GuildServiceImplTest { - private GuildMemberRepository repository; - private net.firedevops.firemud.socialgroups.client.LoggingAdminClient loggingAdminClient; + private GuildMemberRepository memberRepository; + private GuildRepository guildRepository; private GuildServiceImpl service; @BeforeEach void setUp() { - repository = Mockito.mock(GuildMemberRepository.class); - loggingAdminClient = - Mockito.mock(net.firedevops.firemud.socialgroups.client.LoggingAdminClient.class); + memberRepository = Mockito.mock(GuildMemberRepository.class); + guildRepository = Mockito.mock(GuildRepository.class); service = new GuildServiceImpl( null, null, null, null, - null, - null, - repository, - Mappers.getMapper(GuildMemberMapper.class), - loggingAdminClient); + guildRepository, + Mappers.getMapper(GuildMapper.class), + memberRepository, + Mappers.getMapper(GuildMemberMapper.class)); } @Test - void addMemberReturnsDto() throws Exception { + void addMemberReturnsDto() { AddGuildMemberRequest request = new AddGuildMemberRequest(1L, 2L, accountUuid(3L), "member"); - GuildMember saved = new GuildMember(); - saved.setId(1L); - saved.setTenantId(1L); - saved.setGuildId(2L); - saved.setAccountId(accountUuid(3L)); - saved.setRole("member"); - when(repository.save(any(GuildMember.class))).thenReturn(saved); + GuildMember saved = member("member"); + when(memberRepository.save(any(GuildMember.class))).thenReturn(saved); GuildMemberDto dto = service.addMember(request); + assertEquals(accountUuid(3L), dto.accountId()); assertEquals("member", dto.role()); - verify(loggingAdminClient).reportChatViolation(1L, accountUuid(3L), "Joined guild 2"); } @Test - void updateMemberRoleUsesRepositoryLookup() throws Exception { - GuildMember member = new GuildMember(); - member.setId(5L); - member.setTenantId(1L); - member.setGuildId(2L); - member.setAccountId(accountUuid(3L)); - member.setRole("member"); - when(repository.findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, accountUuid(3L))) + void updateMemberRoleUsesRepositoryLookup() { + GuildMember member = member("member"); + when(memberRepository.findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, accountUuid(3L))) .thenReturn(java.util.Optional.of(member)); GuildMemberDto dto = @@ -73,26 +65,158 @@ void updateMemberRoleUsesRepositoryLookup() throws Exception { new UpdateGuildMemberRoleRequest(1L, 2L, accountUuid(3L), "officer")); assertEquals("officer", dto.role()); - verify(repository).findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, accountUuid(3L)); - verify(loggingAdminClient) - .reportChatViolation(1L, accountUuid(3L), "Updated guild role to officer"); + verify(memberRepository).findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, accountUuid(3L)); } @Test - void removeMemberUsesRepositoryLookup() throws Exception { + void removeMemberUsesRepositoryLookup() { + GuildMember member = member("member"); + when(memberRepository.findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, accountUuid(3L))) + .thenReturn(java.util.Optional.of(member)); + + service.removeMember(1L, 2L, accountUuid(3L)); + + verify(memberRepository).findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, accountUuid(3L)); + verify(memberRepository).delete(member); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.CsvSource({ + "CREATE,true", + "CREATE,false", + "ADD_MEMBER,true", + "ADD_MEMBER,false", + "UPDATE_MEMBER_ROLE,true", + "UPDATE_MEMBER_ROLE,false", + "REMOVE_MEMBER,true", + "REMOVE_MEMBER,false" + }) + void lifecycleLoggingHasCommittedContextAndDoesNotRunOnRollback(String action, boolean commit) { + var logger = + (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(GuildServiceImpl.class); + var events = + new ch.qos.logback.core.read.ListAppender(); + events.start(); + logger.addAppender(events); + org.springframework.transaction.support.TransactionSynchronizationManager.initSynchronization(); + try { + performLifecycle(action); + org.junit.jupiter.api.Assertions.assertTrue( + events.list.stream() + .noneMatch( + event -> event.getFormattedMessage().startsWith("Guild lifecycle committed"))); + var callbacks = + org.springframework.transaction.support.TransactionSynchronizationManager + .getSynchronizations(); + if (commit) { + callbacks.forEach( + org.springframework.transaction.support.TransactionSynchronization::afterCommit); + } + callbacks.forEach(callback -> callback.afterCompletion(commit ? 0 : 1)); + var lifecycle = + events.list.stream() + .filter(event -> event.getFormattedMessage().startsWith("Guild lifecycle committed")) + .toList(); + assertEquals(commit ? 1 : 0, lifecycle.size()); + if (commit) { + assertEquals( + "Guild lifecycle committed tenant=1 guild=2 account=" + + accountUuid(3L) + + " action=" + + action + + " role=" + + (action.equals("CREATE") + ? "null" + : action.equals("UPDATE_MEMBER_ROLE") ? "officer" : "member"), + lifecycle.getFirst().getFormattedMessage()); + } + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager + .clearSynchronization(); + logger.detachAppender(events); + events.stop(); + } + } + + @Test + @SuppressWarnings("unchecked") + void throwingLifecycleAppenderCannotFailAlreadyCommittedMutation() { + var logger = + (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(GuildServiceImpl.class); + ch.qos.logback.core.Appender appender = + Mockito.mock(ch.qos.logback.core.Appender.class); + var attempted = new java.util.concurrent.atomic.AtomicBoolean(); + Mockito.doAnswer( + invocation -> { + ch.qos.logback.classic.spi.ILoggingEvent event = invocation.getArgument(0); + if (event.getFormattedMessage().startsWith("Guild lifecycle committed")) { + attempted.set(true); + throw new IllegalStateException("controlled logging failure"); + } + return null; + }) + .when(appender) + .doAppend(any(ch.qos.logback.classic.spi.ILoggingEvent.class)); + logger.addAppender(appender); + org.springframework.transaction.support.TransactionSynchronizationManager.initSynchronization(); + try { + performLifecycle("ADD_MEMBER"); + verify(memberRepository).save(any(GuildMember.class)); + org.junit.jupiter.api.Assertions.assertFalse(attempted.get()); + org.junit.jupiter.api.Assertions.assertDoesNotThrow( + () -> + org.springframework.transaction.support.TransactionSynchronizationManager + .getSynchronizations() + .forEach( + org.springframework.transaction.support.TransactionSynchronization + ::afterCommit)); + org.junit.jupiter.api.Assertions.assertTrue(attempted.get()); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager + .clearSynchronization(); + logger.detachAppender(appender); + } + } + + private void performLifecycle(String action) { + GuildMember member = member("member"); + switch (action) { + case "CREATE" -> { + when(guildRepository.save(any(Guild.class))) + .thenAnswer( + invocation -> { + Guild guild = invocation.getArgument(0); + guild.setId(2L); + return guild; + }); + service.createGuild(new CreateGuildRequest(1L, accountUuid(3L), "guild")); + } + case "ADD_MEMBER" -> { + when(memberRepository.save(any(GuildMember.class))).thenReturn(member); + service.addMember(new AddGuildMemberRequest(1L, 2L, accountUuid(3L), "member")); + } + case "UPDATE_MEMBER_ROLE" -> { + when(memberRepository.findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, accountUuid(3L))) + .thenReturn(java.util.Optional.of(member)); + service.updateMemberRole( + new UpdateGuildMemberRoleRequest(1L, 2L, accountUuid(3L), "officer")); + } + case "REMOVE_MEMBER" -> { + when(memberRepository.findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, accountUuid(3L))) + .thenReturn(java.util.Optional.of(member)); + service.removeMember(1L, 2L, accountUuid(3L)); + } + default -> throw new IllegalArgumentException("Unknown lifecycle action"); + } + } + + private GuildMember member(String role) { GuildMember member = new GuildMember(); member.setId(5L); member.setTenantId(1L); member.setGuildId(2L); member.setAccountId(accountUuid(3L)); - member.setRole("member"); - when(repository.findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, accountUuid(3L))) - .thenReturn(java.util.Optional.of(member)); - - service.removeMember(1L, 2L, accountUuid(3L)); - - verify(repository).findFirstByTenantIdAndGuildIdAndAccountId(1L, 2L, accountUuid(3L)); - verify(repository).delete(member); - verify(loggingAdminClient).reportChatViolation(1L, accountUuid(3L), "Left guild 2"); + member.setRole(role); + return member; } } 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 e7a35f4ffd..9f0818f39b 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 @@ -10,7 +10,10 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.Instant; import java.util.List; +import java.util.Map; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.socialgroups.dto.CreateGuildRequest; import net.firedevops.firemud.socialgroups.dto.FriendPresenceDto; import net.firedevops.firemud.socialgroups.dto.FriendPresencePolicyViewDto; import net.firedevops.firemud.socialgroups.dto.FriendPresenceVisibilityPolicyValue; @@ -19,6 +22,7 @@ import net.firedevops.firemud.socialgroups.dto.FriendRosterFilter; import net.firedevops.firemud.socialgroups.dto.FriendRosterSummaryDto; import net.firedevops.firemud.socialgroups.dto.FriendRosterViewDto; +import net.firedevops.firemud.socialgroups.dto.GuildDto; import net.firedevops.firemud.socialgroups.dto.SendMessageRequestDto; import net.firedevops.firemud.socialgroups.enums.ChatType; import net.firedevops.firemud.socialgroups.security.SocialAccessGuard; @@ -85,7 +89,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, accountUuid(2L))).thenReturn(true); + Mockito.when(accessGuard.hasGuildOwnerAccess(1L, accountUuid(2L))).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -123,7 +127,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, accountUuid(2L))).thenReturn(true); + Mockito.when(accessGuard.hasGuildOwnerAccess(1L, accountUuid(2L))).thenReturn(true); SocialGroupsGrpcService service = new SocialGroupsGrpcService( ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); @@ -152,6 +156,91 @@ public void onCompleted() {} assertEquals("INTERNAL", ref.get().getError().getCode()); } + @Test + void createGuildAllowsOrdinaryUuidCallerToCreateForExactSelf() { + SessionContext.setContext(accountUuid(2L), List.of(), Map.of()); + try { + PingService ping = Mockito.mock(PingService.class); + ChatService chat = Mockito.mock(ChatService.class); + GuildService guild = Mockito.mock(GuildService.class); + FriendService friend = Mockito.mock(FriendService.class); + MailService mail = Mockito.mock(MailService.class); + whenGuildCreated(guild); + SocialGroupsGrpcService service = + new SocialGroupsGrpcService( + ping, chat, guild, friend, mail, new SocialAccessGuard(), new SimpleMeterRegistry()); + + AtomicReference ref = new AtomicReference<>(); + service.createGuild( + net.firedevops.firemud.socialgroups.v1.CreateGuildRequest.newBuilder() + .setTenantId("1") + .setOwnerAccountId(accountUuid(2L)) + .setName("test") + .build(), + new StreamObserver<>() { + @Override + public void onNext(CreateGuildResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }); + + assertNotNull(ref.get()); + assertEquals("5", ref.get().getGuildId()); + verify(guild).createGuild(new CreateGuildRequest(1L, accountUuid(2L), "test")); + } finally { + SessionContext.clear(); + } + } + + @Test + void createGuildRejectsOtherOwnerWithoutTenantPrivilegeBeforeDispatch() { + PingService ping = Mockito.mock(PingService.class); + ChatService chat = Mockito.mock(ChatService.class); + GuildService guild = Mockito.mock(GuildService.class); + FriendService friend = Mockito.mock(FriendService.class); + MailService mail = Mockito.mock(MailService.class); + SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); + Mockito.when(accessGuard.hasGuildOwnerAccess(1L, accountUuid(3L))).thenReturn(false); + SocialGroupsGrpcService service = + new SocialGroupsGrpcService( + ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); + + AtomicReference ref = new AtomicReference<>(); + service.createGuild( + net.firedevops.firemud.socialgroups.v1.CreateGuildRequest.newBuilder() + .setTenantId("1") + .setOwnerAccountId(accountUuid(3L)) + .setName("test") + .build(), + new StreamObserver<>() { + @Override + public void onNext(CreateGuildResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }); + + assertNotNull(ref.get()); + assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); + verifyNoInteractions(guild); + } + + private static void whenGuildCreated(GuildService guild) { + Mockito.when(guild.createGuild(Mockito.any())) + .thenReturn(new GuildDto(5L, 1L, "test", accountUuid(2L), Instant.now())); + } + @Test void sendMessageMapsWhisperProtoToDomainEnum() { PingService ping = Mockito.mock(PingService.class); @@ -279,7 +368,49 @@ 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); + } + + @Test + void sendMessageRejectsPaddedOptionalRecipientUuidBeforeDispatch() { + PingService ping = Mockito.mock(PingService.class); + ChatService chat = Mockito.mock(ChatService.class); + GuildService guild = Mockito.mock(GuildService.class); + FriendService friend = Mockito.mock(FriendService.class); + MailService mail = Mockito.mock(MailService.class); + SocialAccessGuard accessGuard = Mockito.mock(SocialAccessGuard.class); + Mockito.when(accessGuard.hasAccountAccess(1L, accountUuid(2L))).thenReturn(true); + SocialGroupsGrpcService service = + new SocialGroupsGrpcService( + ping, chat, guild, friend, mail, accessGuard, new SimpleMeterRegistry()); + + AtomicReference ref = new AtomicReference<>(); + service.sendMessage( + net.firedevops.firemud.socialgroups.v1.SendMessageRequest.newBuilder() + .setTenantId("1") + .setSenderId(accountUuid(2L)) + .setType(net.firedevops.firemud.socialgroups.v1.ChatType.CHAT_TYPE_TELL) + .setRecipientId(" " + accountUuid(7L)) + .setContent("hello") + .build(), + new StreamObserver<>() { + @Override + public void onNext(SendMessageResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }); + + assertNotNull(ref.get()); + assertEquals(false, ref.get().getSuccess()); + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + assertEquals("Malformed claim: recipientId", ref.get().getError().getMessage()); verifyNoInteractions(chat); } From effade55cc1e51e66062fd046ece05b0192606fe Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 30 Oct 2026 22:24:36 +1300 Subject: [PATCH 05/34] Qualify received UUID JOIN responses with future caller identity --- .../player-access-and-session.md | 3 ++- .../service/impl/AccountGrpcService.java | 3 ++- .../AccountApplicationIntegrationTest.java | 7 ++++++- .../service/impl/AccountGrpcServiceTest.java | 13 +++---------- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 1a5d454943..39afc97bbd 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -507,6 +507,7 @@ The response-only Account source projects canonical persisted Account UUIDs in e Focused service/controller/gRPC cases and native PostgreSQL composition have been extended for UUID responses, generated profile mapping, retained private rows, replay, owner readback refusal and current numeric-selector caller behavior; R1186 failed as recorded below, and R1189 qualifies the corrected source in the stated scope. Earlier source results retain their own attribution. Within the published response-only boundary, request selectors, ordinary JWT identity and shared forwarding remained outside scope; the separate local receiving preparation below carries their unpublished changes. Canonical profile routes/authorization, token registry qualification and gameplay activation remain separate gaps. No production Game Session text-JOIN caller is introduced, and the unavailable JOIN route remains absent from public OpenAPI. R1186 executed 1,701 Account unit cases (1,696 passed, one failed and four skipped) and seven native Account application cases (six passed and one failed). The extended JOIN recovery test retained a stale three-read assertion after adding a fourth locked entitlement read; the native case reached its service UUID projections but its authenticated HTTP profile request returned 403. Its test-only `application.yml` shadowed the main configuration and omitted HTTP interceptor enablement. The native suite now imports a distinctly named build-time copy of the canonical main application configuration, retaining its actual HTTP policy and public routes, with explicit HTTP-property/interceptor assertions and response-body diagnostics. Controlled test PKI/server overrides remain, with private port-zero gRPC and workload namespace `test`; this is not production PKI or namespace qualification. The nullable final native row assertion and stale read count are corrected in the receiving source. Main/unit analysis, integration Checkstyle, links and Markdown passed in R1186; integration SpotBugs reported the nullable row assertion, and Spotless check was up-to-date after application. R1189 passes the corrected complete Account unit task (1,697 passed, zero failures/errors and four existing conditional trust-permission skips) and all seven native application cases without failures or skips. The native case verifies the actual imported HTTP policy and interceptor, then exercises genuine ordinary-JWT profile HTTP access alongside JOIN/replay and profile/export projection with retained private SQL rows. Enabled main/unit/native analysis, formatting and documentation checks pass. This is focused component and HTTP proof with controlled test transport and namespace; independent review, full native-service execution, current published-head CI and production activation remain separate obligations. + #### Ordinary Account UUID receiving preparation Unpublished #2972 local source postimages move Account authentication and player-bootstrap results, issued JWT account subjects/claims, and profile Account fields to the persisted Account UUID. Account resolves UUID to a private numeric row only through its own persisted UUID, provenance, and source-row checks. Social REST/gRPC DTOs and jOOQ-backed Account carriers use UUID fields; Logging's ordinary moderation receiver uses Account UUIDs. Tenant identifiers retain their current numeric representation. These are local receiving consequences, not a published or review-ready capability. @@ -517,7 +518,7 @@ Proof is partial and not an aggregate pass. R1101 retained its aggregate failure R1179 qualifies the subsequent local receiving corrections with seven Account native application cases, 22 Social native/migration cases and three Game Session WebSocket communication cases, all passing without skips. Retained unit results are Account 1783 reported with four existing conditional trust-permission skips, Social 138, Common Security 271 and 165 selected Game Session cases; requested formatting checks pass. Genuine password and verified-email OTP HTTP credentials carry persisted Account UUID identity through signature verification, the shared session context and the actual Social CreateGuild handler/access guard. Guild storage is mocked in that bridge; separate Social native proof covers its storage boundary. Moderator authority is assigned by a controlled persisted fixture, and communication uses its controlled Account runtime collaborator. These results do not prove real Social transport, production authority, full service/static qualification, current-parent qualification or a review-ready publication. Earlier R1170/R1173/R1175/R1177 failed aggregates retain their source attribution; the tested fixture and compilation corrections do not establish a production defect. Reconciliation with the newly published #3352 parent is pending fresh affected proof. -Local reconciliation now receives the response-only source and its corrected main-configuration native proof while retaining the future ordinary UUID issuer, request selectors and caller preparation. Historical R1189 evidence qualifies its original response-only source, not this merged composition; fresh integrated proof is **unrun**. No publication, default registration, production custody/PKI or activation hold is cleared by this receipt. +Local reconciliation receives the response-only source and its corrected main-configuration native proof while retaining the future ordinary UUID issuer, request selectors and caller preparation. R1197 and R1198 first fail compilation on retained numeric JOIN-result comparisons and a test constructor after the response becomes a UUID string; R1197 also finds a missing Markdown heading blank line. The corrected result guard compares the response UUID to the already validated wire caller and retains the private numeric caller only within Account. R1200 then passes the complete Account unit task (1,783 passed, four existing conditional skips) and all seven native application cases, with enabled affected main/unit/native analysis, formatting and documentation checks passing. Historical R1189 evidence remains attributed to its original response-only source. This focused receiving proof does not establish a published full-service pass, default registration, production custody/PKI or activation. ### Text Protocol and Credential Policy 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 f601a69a14..04e6d1cbb8 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 @@ -179,7 +179,8 @@ public void joinPublicProductionMembership( caller, new JoinPublicProductionRequest( requireText(request.getConnectScopeId(), "connectScopeId"), requestId)); - if (result.accountId() != caller.accountId() || result.tenantId() != caller.tenantId()) { + if (!request.getPlayerContext().getAccountId().equals(result.accountId()) + || result.tenantId() != caller.tenantId()) { throw new IllegalStateException("Account JOIN result does not match the validated caller"); } response diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index 63b08ed312..a856a75fe7 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -644,7 +644,12 @@ public void onCompleted() {} HTTP_CLIENT.send( HttpRequest.newBuilder( URI.create( - "http://localhost:" + port + "/profiles/" + account.id() + "?tenantId=" + tenant)) + "http://localhost:" + + port + + "/profiles/" + + account.id() + + "?tenantId=" + + tenant)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + ordinary) .GET() .build(), 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 c2541bc303..1f0e2094f8 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 @@ -295,14 +295,7 @@ void joinPublicProductionMembershipPreservesStoredFailureOutcome() { Mockito.any(JoinPublicProductionRequest.class))) .thenReturn( new JoinPublicProductionResult( - false, - "ENTITLEMENT_UNAVAILABLE", - ACCOUNT_UUID, - 20L, - 0L, - 0L, - 0L, - true)); + false, "ENTITLEMENT_UNAVAILABLE", ACCOUNT_UUID, 20L, 0L, 0L, 0L, true)); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); @@ -607,7 +600,7 @@ void directTextMethodsRejectNoncanonicalAccountBeforeOwnerLookup(String accountI @ParameterizedTest @ValueSource(booleans = {true, false}) - void joinRejectsPrivateResultThatDoesNotMatchValidatedCaller(boolean changedAccount) { + void joinRejectsUuidResultThatDoesNotMatchValidatedCaller(boolean changedAccount) { AccountService owner = Mockito.mock(AccountService.class); Mockito.when(owner.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))).thenReturn(10L); Mockito.when(owner.joinPublicProductionFromGameSession(Mockito.any(), Mockito.any())) @@ -615,7 +608,7 @@ void joinRejectsPrivateResultThatDoesNotMatchValidatedCaller(boolean changedAcco new JoinPublicProductionResult( false, "ENTITLEMENT_UNAVAILABLE", - changedAccount ? 11L : 10L, + changedAccount ? OTHER_ACCOUNT_UUID : ACCOUNT_UUID, changedAccount ? 20L : 21L, 0L, 0L, From aed976420125774a758c4a2ebc7cfb8ef394b2f6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 30 Oct 2026 22:55:48 +1300 Subject: [PATCH 06/34] Record qualified ordinary UUID profile receiving proof --- .../player-access-and-session.md | 2 +- .../controller/ProfileControllerTest.java | 20 +++++++++++-------- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index f504ae0f34..cc55161e9f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -513,7 +513,7 @@ R1186 executed 1,701 Account unit cases (1,696 passed, one failed and four skipp The published B boundary changed legacy `GET /profiles/{accountId}?tenantId=...` and `PUT /profiles/{accountId}` selectors now accept only canonical lowercase non-nil Account UUIDs. PUT's body selector must equal the path selector. The controller resolves the UUID through Account's existing persisted-provenance/source-row resolver, then preserves the current numeric `SessionContext` self-binding and Account service membership check. Reserved presence-policy refusal and post-commit update notification remain in place. This changes only Account REST request identity; ordinary JWT identities, shared forwarding, gRPC `UpdateProfileRequest`, the live Social numeric snapshot selector, and the legacy route/authorization policy remain unchanged and tracked as drift. `ProfileControllerTest` adds canonical GET/PUT, numeric/malformed/nil path and body rejection, path/body mismatch, numeric-session wrong-owner refusal, and `AUTH_UNAVAILABLE` mapping for inconsistent or unavailable owner resolution. The native Account application case uses the canonical imported main HTTP configuration and an Account-issued ordinary credential to cover UUID GET/PUT success, selector rejection, mismatch, wrong-owner refusal, missing tenant membership, and reserved-policy refusal while checking the retained numeric profile row. R1202 passes the complete Account unit task (1,701 passed, four existing conditional skips) and all seven native application cases, with zero failures or errors. Enabled main/unit/native analysis, formatting and documentation checks also pass. This is focused local proof; current published-head CI and independent review remain outstanding. The V29 database trigger makes persisted UUID/provenance/source-row fields immutable, so this native fixture cannot corrupt owner evidence; existing Account resolver unit coverage plus the new controller exception cases cover that failure mapping. Existing test transport and workload namespace remain controlled and are not production PKI/namespace proof. -Local receipt of the REST selector source preserves the future UUID ordinary issuer, shared UUID context/self-binding, internal/gRPC UUID update contracts and callers while receiving the REST-specific DTO, path/body checks, bounded owner resolution, export owner reuse and main-config HTTP proof. R1202 remains evidence for B’s historical legacy-token source; this newly merged future composition is **unrun**. Default registration, production custody/PKI, canonical profile authorization and public activation remain held. +Local receipt of the REST selector source preserves the future UUID ordinary issuer, shared UUID context/self-binding, internal/gRPC UUID update contracts and callers while receiving the REST-specific DTO, path/body checks, bounded owner resolution, export owner reuse and main-config HTTP proof. R1202 remains evidence for B’s historical legacy-token source. R1204 qualifies this merged future Account composition with 1,787 passing unit cases, four existing conditional skips and all seven native application cases passing; enabled affected analysis, formatting and documentation checks pass. This is focused receiving evidence, not a whole-source published-service or activation claim. Default registration, production custody/PKI, canonical profile authorization and public activation remain held. #### Ordinary Account UUID receiving preparation diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java index a60313486c..ddf99b1ad5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java @@ -64,8 +64,7 @@ void clear() { void getProfileResolvesCanonicalUuidAndReturnsUuidDto() throws Exception { ProfileDto dto = profileDto(ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); when(accountService.getProfile(1L, 2L)).thenReturn(dto); - when(accountService.resolveAccountStorageId(ACCOUNT_UUID)) - .thenReturn(2L); + when(accountService.resolveAccountStorageId(ACCOUNT_UUID)).thenReturn(2L); mockMvc .perform( @@ -84,7 +83,8 @@ void getProfileResolvesCanonicalUuidAndReturnsUuidDto() throws Exception { @Test void updateProfileResolvesMatchingCanonicalUuidSelectors() throws Exception { UpdateProfileRequest internalRequest = - new UpdateProfileRequest(1L, ACCOUNT_UUID_TEXT, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + new UpdateProfileRequest( + 1L, ACCOUNT_UUID_TEXT, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); when(accountService.updateProfile(internalRequest)) .thenReturn(profileDto(ProfilePresenceVisibilityPolicy.PRIVATE)); @@ -208,7 +208,8 @@ void getProfileRejectsZeroTenantIdBeforeDispatch() throws Exception { @Test void updateProfileAllowsCurrentUuidSessionOwner() throws Exception { UpdateProfileRequest internalRequest = - new UpdateProfileRequest(1L, ACCOUNT_UUID_TEXT, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + new UpdateProfileRequest( + 1L, ACCOUNT_UUID_TEXT, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); when(accountService.updateProfile(internalRequest)) .thenReturn(profileDto(ProfilePresenceVisibilityPolicy.PRIVATE)); @@ -248,7 +249,8 @@ void updateProfileRejectsReservedHiddenStaffPolicyBeforeDispatch() throws Except @Test void updateProfileRejectsUnauthorizedCallerBeforeReservedPolicyValidation() throws Exception { UpdateProfileRestRequest request = restRequest(ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); - String token = jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("accountId", OTHER_ACCOUNT_UUID)); + String token = + jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("accountId", OTHER_ACCOUNT_UUID)); mockMvc .perform( @@ -287,7 +289,10 @@ void updateProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { @Test void updateProfileRejectsGlobalAdminForAnotherAccount() throws Exception { - String token = jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -434,8 +439,7 @@ void updateProfileRejectsChangedBodyAccountBeforeDispatch() throws Exception { @Test void getProfileRefusesWrongOwnerProjection() throws Exception { - when(accountService.resolveAccountStorageId(ACCOUNT_UUID)) - .thenReturn(2L); + when(accountService.resolveAccountStorageId(ACCOUNT_UUID)).thenReturn(2L); when(accountService.getProfile(1L, 2L)) .thenReturn( new ProfileDto( From 5c5efdb0c81255e6149e4ce5b036da0f406bc34e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 00:02:25 +1300 Subject: [PATCH 07/34] Align ordinary UUID consumer authentication fixtures --- .../controller/AccountControllerTest.java | 24 +++++++++----- .../client/GameLogicClientTest.java | 7 ++-- .../controller/FeatureFlagControllerTest.java | 14 ++++++-- .../GameSessionPinControllerTest.java | 14 +++++--- .../GameplayCommandControllerTest.java | 19 ++++++++--- .../controller/LogQueryControllerTest.java | 14 ++++++-- .../ModerationActionControllerTest.java | 14 ++++++-- .../TickRemediationControllerTest.java | 32 +++++++++++-------- 8 files changed, 95 insertions(+), 43 deletions(-) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java index 33ff4d26a7..836554e72f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java @@ -123,7 +123,10 @@ void createAccountRetainsMinimumPasswordLength() throws Exception { @Test void deleteAccountAllowsGlobalPlatformAdmin() throws Exception { when(accountService.resolveAccountStorageId(ACCOUNT_UUID)).thenReturn(ACCOUNT_ROW_ID); - String token = jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -177,8 +180,7 @@ void exportAccountAllowsCurrentAccountWithoutTenantScope() throws Exception { null, net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy .FRIENDS_ONLY)))); - when(accountService.resolveAccountStorageId(ACCOUNT_UUID)) - .thenReturn(42L); + when(accountService.resolveAccountStorageId(ACCOUNT_UUID)).thenReturn(42L); String token = jwtUtil.generateToken(ACCOUNT_UUID_TEXT, Map.of("accountId", ACCOUNT_UUID_TEXT)); mockMvc @@ -201,8 +203,7 @@ void exportTenantDataAllowsScopedTenantRole() throws Exception { "4cae05e8-7a6b-4b14-9d44-665e3eec450b", "demo", "demo@example.com", "player", true); when(accountService.exportTenantData(7L, ACCOUNT_ROW_ID)) .thenReturn(new TenantDataExportDto(7L, account, null)); - when(accountService.resolveAccountStorageId(ACCOUNT_UUID)) - .thenReturn(42L); + when(accountService.resolveAccountStorageId(ACCOUNT_UUID)).thenReturn(42L); String token = jwtUtil.generateToken( OTHER_ACCOUNT_UUID, @@ -224,7 +225,8 @@ void exportTenantDataAllowsScopedTenantRole() throws Exception { @Test void accountSubjectCannotSelectAnotherAccountWithoutGlobalPrivilege() throws Exception { when(accountService.resolveAccountStorageId(ACCOUNT_UUID)).thenReturn(43L); - String token = jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("accountId", OTHER_ACCOUNT_UUID)); + String token = + jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("accountId", OTHER_ACCOUNT_UUID)); mockMvc .perform( @@ -253,7 +255,10 @@ void accountSubjectCannotSelectAnotherAccountWithoutGlobalPrivilege() throws Exc @Test void allAccountSelectorRoutesRejectMalformedNumericNilAndNoncanonicalUuidsBeforeDispatch() throws Exception { - String token = jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); List invalidSelectors = List.of( "42", @@ -280,7 +285,10 @@ void allAccountSelectorRoutesRejectMalformedNumericNilAndNoncanonicalUuidsBefore @Test void exportTenantDataRejectsZeroTenantIdBeforeDispatch() throws Exception { when(accountService.resolveAccountStorageId(ACCOUNT_UUID)).thenReturn(ACCOUNT_ROW_ID); - String token = jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, + Map.of("accountId", OTHER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java index 40acdad3ec..240f2e70ac 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java @@ -439,7 +439,7 @@ void sendCommunicationRejectsInvalidAccountUuidBeforeRpc() throws Exception { null, null)) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("accountId"); + .hasMessageContaining("canonical non-nil Account UUID"); } verify(stub, never()).sendCommunication(any(SendCommunicationRequest.class)); @@ -573,8 +573,7 @@ void dropCarriedItemRejectsInvalidAccountUuidBeforeDispatch() throws Exception { setStub(client, stub); assertInvalidAccountUuidsAreRejectedBeforeRpc( - accountId -> - client.dropCarriedItem(sessionContextWithAccountId(accountId), "torch1", 1)); + accountId -> client.dropCarriedItem(sessionContextWithAccountId(accountId), "torch1", 1)); verify(stub, never()).dropCarriedItem(any(DropCarriedItemRequest.class)); } @@ -707,7 +706,7 @@ private static void assertInvalidAccountUuidsAreRejectedBeforeRpc( }) { assertThatThrownBy(() -> invocation.accept(accountId)) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("canonical non-nil Account UUID"); + .hasMessageContaining("accountId"); } } diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/FeatureFlagControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/FeatureFlagControllerTest.java index 291f8b924f..f554d00580 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/FeatureFlagControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/FeatureFlagControllerTest.java @@ -34,6 +34,8 @@ @WithFiremudPrivilegedHttpAuthTestProperties class FeatureFlagControllerTest { + private static final String ACCOUNT_ID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + @Autowired private MockMvc mockMvc; private final ObjectMapper objectMapper = new ObjectMapper(); @@ -47,7 +49,9 @@ void clear() { @Test void toggleRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Exception { ToggleFeatureFlagRequest request = new ToggleFeatureFlagRequest(1L, "demo", true); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -68,7 +72,9 @@ void toggleRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Except void toggleRejectsCrossTenantScopedAdmin() throws Exception { ToggleFeatureFlagRequest request = new ToggleFeatureFlagRequest(1L, "demo", true); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + jwtUtil.generateToken( + ACCOUNT_ID, + Map.of("accountId", ACCOUNT_ID, "scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -82,7 +88,9 @@ void toggleRejectsCrossTenantScopedAdmin() throws Exception { @Test void toggleRejectsZeroTenantIdBeforeDispatch() throws Exception { ToggleFeatureFlagRequest request = new ToggleFeatureFlagRequest(0L, "demo", true); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/GameSessionPinControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/GameSessionPinControllerTest.java index b8f183acef..9ab6b9cb2e 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/GameSessionPinControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/GameSessionPinControllerTest.java @@ -32,6 +32,8 @@ @Import({CommonSecurityAutoConfiguration.class, CommonSecurityServletAutoConfiguration.class}) @WithFiremudPrivilegedHttpAuthTestProperties class GameSessionPinControllerTest { + private static final String ACCOUNT_ID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + @Autowired private MockMvc mockMvc; @Autowired private JwtUtil jwtUtil; @@ -47,7 +49,7 @@ void getPinnedScriptPatchVersionReturnsPinMetadata() throws Exception { when(gameSessionPinService.getPinnedScriptPatchVersion(1L, 7L)).thenReturn(pinnedVersionDto()); String token = jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform(get("/game-session-pins/1/7").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -62,7 +64,7 @@ void getGameSessionPinConvergenceReturnsConvergenceMetadata() throws Exception { .thenReturn(pinConvergenceDto()); String token = jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -77,7 +79,9 @@ void getGameSessionPinConvergenceReturnsConvergenceMetadata() throws Exception { @Test void getPinnedScriptPatchVersionRejectsCrossTenantScopedAdmin() throws Exception { String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + jwtUtil.generateToken( + ACCOUNT_ID, + Map.of("accountId", ACCOUNT_ID, "scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform(get("/game-session-pins/1/7").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -88,7 +92,7 @@ void getPinnedScriptPatchVersionRejectsCrossTenantScopedAdmin() throws Exception void getPinnedScriptPatchVersionRejectsMalformedTenantIdBeforeDispatch() throws Exception { String token = jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -105,7 +109,7 @@ void getPinnedScriptPatchVersionRejectsMalformedTenantIdBeforeDispatch() throws void getGameSessionPinConvergenceRejectsZeroGameInstanceIdBeforeDispatch() throws Exception { String token = jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/GameplayCommandControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/GameplayCommandControllerTest.java index 6b989ce7b4..6def8bbe7a 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/GameplayCommandControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/GameplayCommandControllerTest.java @@ -47,7 +47,10 @@ void getGameplayCommandStatusReturnsCanonicalStatus() throws Exception { when(gameplayCommandStatusService.getGameplayCommandStatus(2L, 7L, "cmd-123")) .thenReturn(gameplayCommandStatusDto()); SessionContext.setContext(ACCOUNT_UUID, List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -65,7 +68,9 @@ void getGameplayCommandStatusReturnsCanonicalStatus() throws Exception { void getGameplayCommandStatusRejectsCrossTenantScopedAdmin() throws Exception { SessionContext.setContext(ACCOUNT_UUID, List.of(), Map.of("8", List.of("tenantAdmin"))); String token = - jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID, "scopedRoles", Map.of("8", List.of("tenantAdmin")))); + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -77,7 +82,10 @@ void getGameplayCommandStatusRejectsCrossTenantScopedAdmin() throws Exception { @Test void getGameplayCommandStatusRejectsZeroTenantIdBeforeDispatch() throws Exception { SessionContext.setContext(ACCOUNT_UUID, List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -93,7 +101,10 @@ void getGameplayCommandStatusRejectsZeroTenantIdBeforeDispatch() throws Exceptio @Test void getGameplayCommandStatusRejectsZeroGameInstanceIdBeforeDispatch() throws Exception { SessionContext.setContext(ACCOUNT_UUID, List.of("platformAdmin"), Map.of()); - String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_UUID, + Map.of("accountId", ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/LogQueryControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/LogQueryControllerTest.java index 42a0ea8083..560b5a023c 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/LogQueryControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/LogQueryControllerTest.java @@ -38,6 +38,8 @@ @WithFiremudPrivilegedHttpAuthTestProperties class LogQueryControllerTest { + private static final String ACCOUNT_ID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + @Autowired private MockMvc mockMvc; private final ObjectMapper objectMapper = new ObjectMapper(); @@ -53,7 +55,9 @@ void clear() { void queryReturnsEntries() throws Exception { QueryLogsRequest request = new QueryLogsRequest(1L, "msg"); when(service.queryLogs(request)).thenReturn(List.of("hello")); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -69,7 +73,9 @@ void queryReturnsEntries() throws Exception { void queryRejectsCrossTenantScopedAdmin() throws Exception { QueryLogsRequest request = new QueryLogsRequest(1L, "msg"); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + jwtUtil.generateToken( + ACCOUNT_ID, + Map.of("accountId", ACCOUNT_ID, "scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -83,7 +89,9 @@ void queryRejectsCrossTenantScopedAdmin() throws Exception { @Test void queryRejectsZeroTenantIdBeforeDispatch() throws Exception { QueryLogsRequest request = new QueryLogsRequest(0L, "msg"); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java index 212f29fbd6..031b044e69 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java @@ -37,6 +37,8 @@ @WithFiremudPrivilegedHttpAuthTestProperties class ModerationActionControllerTest { + private static final String ACCOUNT_ID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + @Autowired private MockMvc mockMvc; private final ObjectMapper objectMapper = new ObjectMapper(); @@ -52,7 +54,9 @@ void clear() { void applyRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Exception { ApplyModerationActionRequest req = new ApplyModerationActionRequest(1L, "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", 9L, "ban", ""); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -76,7 +80,9 @@ void applyRejectsCrossTenantScopedAdmin() throws Exception { ApplyModerationActionRequest req = new ApplyModerationActionRequest(1L, "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", 9L, "ban", ""); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("moderator")))); + jwtUtil.generateToken( + ACCOUNT_ID, + Map.of("accountId", ACCOUNT_ID, "scopedRoles", Map.of("8", List.of("moderator")))); mockMvc .perform( @@ -91,7 +97,9 @@ void applyRejectsCrossTenantScopedAdmin() throws Exception { void applyRejectsZeroSessionIdBeforeDispatch() throws Exception { ApplyModerationActionRequest req = new ApplyModerationActionRequest(1L, "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", 0L, "ban", ""); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken( + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/TickRemediationControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/TickRemediationControllerTest.java index 674a5aa069..5d8cdf44df 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/TickRemediationControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/TickRemediationControllerTest.java @@ -38,6 +38,8 @@ }) @WithFiremudPrivilegedHttpAuthTestProperties class TickRemediationControllerTest { + private static final String ACCOUNT_ID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + @Autowired private MockMvc mockMvc; @Autowired private JwtUtil jwtUtil; @@ -72,7 +74,7 @@ void getRuntimeOwnershipStatusReturnsStatusDto() throws Exception { 2000L)); String token = jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -89,7 +91,9 @@ void getRuntimeOwnershipStatusReturnsStatusDto() throws Exception { @Test void getRuntimeOwnershipStatusRejectsCrossTenantScopedAdmin() throws Exception { String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + jwtUtil.generateToken( + ACCOUNT_ID, + Map.of("accountId", ACCOUNT_ID, "scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -104,7 +108,7 @@ void getRuntimeOwnershipStatusRejectsCrossTenantScopedAdmin() throws Exception { void getRuntimeOwnershipStatusRejectsMalformedTenantIdBeforeDispatch() throws Exception { String token = jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -123,7 +127,7 @@ void getRuntimeOwnershipStatusRejectsMalformedTenantIdBeforeDispatch() throws Ex void getRuntimeOwnershipStatusRejectsMalformedGameInstanceIdBeforeDispatch() throws Exception { String token = jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -143,7 +147,7 @@ void pauseRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Excepti TickRemediationRequest request = new TickRemediationRequest(1L, "7", null, "maintenance"); String token = jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -167,7 +171,7 @@ void resumeRejectsAuthorizedCallerWhileMutationGateIsUnavailable() throws Except TickRemediationRequest request = new TickRemediationRequest(1L, "7", null, "maintenance"); String token = jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -192,7 +196,7 @@ void pauseRejectsRegionOnlyScopeBeforeUnavailableResponse() throws Exception { new TickRemediationRequest(1L, null, "region-7", "maintenance"); String token = jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -217,7 +221,7 @@ void resumeRejectsRegionOnlyScopeBeforeUnavailableResponse() throws Exception { new TickRemediationRequest(1L, null, "region-7", "maintenance"); String token = jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -241,7 +245,7 @@ void pauseRejectsEmptyRegionIdBeforeUnavailableResponse() throws Exception { TickRemediationRequest request = new TickRemediationRequest(1L, "7", "", "maintenance"); String token = jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -264,7 +268,7 @@ void resumeRejectsBlankRegionIdBeforeUnavailableResponse() throws Exception { TickRemediationRequest request = new TickRemediationRequest(1L, "7", " ", "maintenance"); String token = jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -286,7 +290,9 @@ void resumeRejectsBlankRegionIdBeforeUnavailableResponse() throws Exception { void resumeRejectsCrossTenantScopedAdmin() throws Exception { TickRemediationRequest request = new TickRemediationRequest(1L, "7", null, "maintenance"); String token = - jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); + jwtUtil.generateToken( + ACCOUNT_ID, + Map.of("accountId", ACCOUNT_ID, "scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( @@ -302,7 +308,7 @@ void pauseRejectsZeroGameInstanceIdBeforeDispatch() throws Exception { TickRemediationRequest request = new TickRemediationRequest(1L, "0", null, "maintenance"); String token = jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -322,7 +328,7 @@ void pauseRejectsZeroTenantIdBeforeDispatch() throws Exception { TickRemediationRequest request = new TickRemediationRequest(0L, "7", null, "maintenance"); String token = jwtUtil.generateToken( - "42", Map.of("accountId", "42", "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( From 344eb4fff4185f25186656b7bb0565e4fb3c4665 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 00:31:23 +1300 Subject: [PATCH 08/34] Record qualified Account UUID receiving proof --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index ad0ec3a57f..1c43dc21f8 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -520,7 +520,7 @@ Local receipt of the REST selector source preserves the future UUID ordinary iss #### Ordinary Account UUID receiving preparation -Current preserved receiving source `5c5efdb0` receives the final original B selector source and qualifies the subsequent fixture corrections: R1209 passes 1,789 Account unit cases with four existing conditional skips and all eight native Account application cases; R1216 freshly passes all 2,822 Game Session and 288 Logging unit cases with no failures, errors or skips, plus affected test analysis and formatting. The later B owner-error and shared-reader fixes are being received separately and require new focused qualification. These results do not establish a whole-source full check, current remote CI, production credential authority or activation. Earlier runs below retain their own attribution. +Current preserved receiving source `16dfb231` receives B's shared Account UUID readers, non-disclosing missing-owner REST denials, and retryable gRPC projection errors while preserving future UUID caller checks before private SQL access, internal UUID contracts and profile response correlation. R1219 freshly passes all 1,794 Account unit cases with four existing conditional skips and all eight native Account application cases; affected main/unit/native analysis, formatting, links and Markdown pass. R1216 separately qualifies all 2,822 Game Session and 288 Logging unit cases with no failures, errors or skips and affected test analysis/formatting on its recorded source. These are focused receiving results, not a whole-source full check, published remote CI, production credential authority or activation. Earlier runs below retain their own attribution. Unpublished #2972 local source postimages move Account authentication and player-bootstrap results, issued JWT account subjects/claims, and profile Account fields to the persisted Account UUID. Account resolves UUID to a private numeric row only through its own persisted UUID, provenance, and source-row checks. Social REST/gRPC DTOs and jOOQ-backed Account carriers use UUID fields; Logging's ordinary moderation receiver uses Account UUIDs. Tenant identifiers retain their current numeric representation. These are local receiving consequences, not a published or review-ready capability. From 6675f36913758a7562030be3884e176e66d58dfe Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 03:45:24 +1300 Subject: [PATCH 09/34] Place moderation UUID migration after shared saga frontier --- ...sql => V1003__moderation_account_uuid.sql} | 0 ...tUuidMigrationPostgresIntegrationTest.java | 37 +++++++++++++++++-- 2 files changed, 34 insertions(+), 3 deletions(-) rename services/logging-admin-service/src/main/resources/db/migration/{V5__moderation_account_uuid.sql => V1003__moderation_account_uuid.sql} (100%) diff --git a/services/logging-admin-service/src/main/resources/db/migration/V5__moderation_account_uuid.sql b/services/logging-admin-service/src/main/resources/db/migration/V1003__moderation_account_uuid.sql similarity index 100% rename from services/logging-admin-service/src/main/resources/db/migration/V5__moderation_account_uuid.sql rename to services/logging-admin-service/src/main/resources/db/migration/V1003__moderation_account_uuid.sql diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java index bd17c82a19..2bcd713099 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.util.List; import java.util.Map; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; @@ -31,13 +32,33 @@ void legacySchema() { new DriverManagerDataSource( postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); Flyway.configure().dataSource(dataSource).cleanDisabled(false).load().clean(); - flyway("4").migrate(); + flyway("1002").migrate(); jdbc = new JdbcTemplate(dataSource); + assertThat( + jdbc.queryForList( + "SELECT version FROM flyway_schema_history WHERE success ORDER BY installed_rank", + String.class)) + .endsWith("1000", "1001", "1002"); + assertThat( + jdbc.queryForObject( + "SELECT script FROM flyway_schema_history WHERE version = '1002' AND success", + String.class)) + .endsWith("V1002__saga_step_table.sql"); } @Test void emptySchemaMigratesAndKeepsExactUuidWithoutChangingPolicyFields() { - flyway("5").migrate(); + List parentHistory = migrationHistory(); + flyway("1003").migrate(); + List migratedHistory = migrationHistory(); + assertThat(migratedHistory).hasSize(parentHistory.size() + 1); + assertThat(migratedHistory.subList(0, parentHistory.size())).isEqualTo(parentHistory); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM flyway_schema_history WHERE version = '1003' " + + "AND script = 'V1003__moderation_account_uuid.sql' AND success", + Integer.class)) + .isOne(); String account = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; jdbc.update( "INSERT INTO moderation_actions (tenant_id, account_id, action, reason) VALUES (1, ?::uuid, 'chat_mute', 'abuse')", @@ -66,7 +87,7 @@ void populatedLegacyRowsBlockMigrationWithoutChangingRowsOrMigrationHistory() { jdbc.queryForObject( "SELECT md5(string_agg(row_to_json(h)::text, ',' ORDER BY installed_rank)) FROM flyway_schema_history h", String.class); - assertThatThrownBy(() -> flyway("5").migrate()) + assertThatThrownBy(() -> flyway("1003").migrate()) .hasStackTraceContaining("Cannot migrate populated legacy moderation Account references"); assertThat( jdbc.queryForObject( @@ -77,6 +98,10 @@ void populatedLegacyRowsBlockMigrationWithoutChangingRowsOrMigrationHistory() { "SELECT md5(string_agg(row_to_json(h)::text, ',' ORDER BY installed_rank)) FROM flyway_schema_history h", String.class)) .isEqualTo(history); + assertThat( + jdbc.queryForObject( + "SELECT count(*) FROM flyway_schema_history WHERE version = '1003'", Integer.class)) + .isZero(); assertThat( jdbc.queryForObject( "SELECT data_type FROM information_schema.columns WHERE table_name = 'moderation_actions' AND column_name = 'account_id'", @@ -84,6 +109,12 @@ void populatedLegacyRowsBlockMigrationWithoutChangingRowsOrMigrationHistory() { .isEqualTo("bigint"); } + private List migrationHistory() { + return jdbc.queryForList( + "SELECT row_to_json(h)::text FROM flyway_schema_history h ORDER BY installed_rank", + String.class); + } + private Flyway flyway(String target) { return Flyway.configure() .dataSource(dataSource) From 9ed08881951dd9a228e1cc726ea0ab37fb4a4334 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:01:47 +1300 Subject: [PATCH 10/34] Describe current UUID cutover capability and proof limits --- .../player-access-and-session.md | 20 +++++-------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 4a3226f308..2d6fc1f8b8 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -520,27 +520,17 @@ Local receipt of the REST selector source preserves the future UUID ordinary iss #### Ordinary Account UUID receiving preparation -Current preserved receiving source `16dfb231` receives B's shared Account UUID readers, non-disclosing missing-owner REST denials, and retryable gRPC projection errors while preserving future UUID caller checks before private SQL access, internal UUID contracts and profile response correlation. R1219 freshly passes all 1,794 Account unit cases with four existing conditional skips and all eight native Account application cases; affected main/unit/native analysis, formatting, links and Markdown pass. R1216 separately qualifies all 2,822 Game Session and 288 Logging unit cases with no failures, errors or skips and affected test analysis/formatting on its recorded source. These are focused receiving results, not a whole-source full check, published remote CI, production credential authority or activation. Earlier runs below retain their own attribution. +The local reconstructed #2972 source converges ordinary password and verified-email OTP issuance, JWT subject/account binding, shared session intake/forwarding, typed Account internal/gRPC inputs, supported Social consumers/storage and Game Session LOGIN/PLAY/session carriers on persisted canonical Account UUIDs. Account alone resolves its UUID to a private row through persisted owner/provenance checks. Logging moderation and Entity roster selectors converge with PLAY; tenant identifiers retain their current numeric representation. The [Account identity contract](../../architecture/microservices/account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity) owns representation and owner resolution. This remains unpublished composition, with final receiving proof pending; the original donor and full final postimages are retained in the controller source record. -Unpublished #2972 local source postimages move Account authentication and player-bootstrap results, issued JWT account subjects/claims, and profile Account fields to the persisted Account UUID. Account resolves UUID to a private numeric row only through its own persisted UUID, provenance, and source-row checks. Social REST/gRPC DTOs and jOOQ-backed Account carriers use UUID fields; Logging's ordinary moderation receiver uses Account UUIDs. Tenant identifiers retain their current numeric representation. These are local receiving consequences, not a published or review-ready capability. +The earlier complete composition has separately attributed proof: R1228 passes 2,840 Game Session units, 22 WebSocket cases, 145 Social units, 16 Social native cases and eight Account native cases, but its aggregate fails Account test compilation. R1230 recovers the corrected Account suite with 1,797 passes and four existing conditional skips, plus affected test analysis/formatting. These are predecessor-source results, not a clean aggregate or current reconstructed-head qualification. Current Social V1003 and Logging V1003 follow their effective shared-saga V1002 parents; R1235 passes seven Social physical PostgreSQL cases, and R1239 passes two Logging physical cases plus generation, parent-aware ordering and affected analysis/formatting. Both migrations lock affected tables, refuse populated legacy references and preserve rows/history without guessed mappings, deletion or backfill. -Social V10 and Logging & Admin V5 lock their affected legacy tables and refuse migration if any retained row exists. Neither migration deletes rows, guesses an Account UUID from a numeric value, or supplies a historical backfill; rollout against populated data requires a genuine Account-owner mapping and explicit retained-data disposition. Fixture Account associations are deterministic only in fake tests and provide no production mapping. Retained numeric Redis session carriers remain fail-closed. The privileged numeric realm-grant DTOs in `InternalRuntimeController`, legacy numeric `LogEvent`/`PlayerReport` fields, the numeric Account deletion client, and the exposed legacy Game Session StartSession owner DTO/proto Account fields remain outside ordinary UUID receiving convergence; no cross-service numeric Account value is treated as private Account provenance. Full JWT profile/registry qualification, default registration, source custody/PKI, and public admission/activation/first `OPEN` remain held and receive no bridge or status change from this preparation. - -Proof is partial and not an aggregate pass. R1101 retained its aggregate failure on the Account helper and jOOQ SQL parsing. R1108 compiled all ten affected modules and passed both jOOQ generations, 14 selected Account unit cases, and two native Logging empty/populated-migration-refusal cases, but failed aggregate execution when Social integration compilation could not see its fixture helper. After the helper was moved unchanged into test fixtures, R1109 passed seven Social native cases; its selected Account run had 22 failures among 344 cases from stale numeric/noncanonical JWT test fixtures and stale UUID gRPC selectors/messages/stubs. R1109 was interrupted during static checks with no exit receipt, so it remains an interrupted partial run, not an aggregate pass. R1110 passes 129 of the 131 selected Account receiver/MVC cases after fixture correction; R1111 separately passes the remaining two after correlating their signed subjects and claims, completing passing execution of all 344 distinct selected Account methods across these runs. R1111 also passes the selected Social fixture/integration and Account test static checks plus documentation, but its aggregate fails one Account main dead-store warning; removing only the unused local value retains the identity-resolution call, and that correction still needs static recovery. At that checkpoint, real registration-to-login HTTP/JWT proof remained unrun; the later receiving executions below supply its focused qualification. No production defect is claimed from the corrected fixture failures, and current full-service qualification remains incomplete. - -R1179 qualifies the subsequent local receiving corrections with seven Account native application cases, 22 Social native/migration cases and three Game Session WebSocket communication cases, all passing without skips. Retained unit results are Account 1783 reported with four existing conditional trust-permission skips, Social 138, Common Security 271 and 165 selected Game Session cases; requested formatting checks pass. Genuine password and verified-email OTP HTTP credentials carry persisted Account UUID identity through signature verification, the shared session context and the actual Social CreateGuild handler/access guard. Guild storage is mocked in that bridge; separate Social native proof covers its storage boundary. Moderator authority is assigned by a controlled persisted fixture, and communication uses its controlled Account runtime collaborator. These results do not prove real Social transport, production authority, full service/static qualification, current-parent qualification or a review-ready publication. Earlier R1170/R1173/R1175/R1177 failed aggregates retain their source attribution; the tested fixture and compilation corrections do not establish a production defect. Reconciliation with the newly published #3352 parent is pending fresh affected proof. - -Local reconciliation receives the response-only source and its corrected main-configuration native proof while retaining the future ordinary UUID issuer, request selectors and caller preparation. R1197 and R1198 first fail compilation on retained numeric JOIN-result comparisons and a test constructor after the response becomes a UUID string; R1197 also finds a missing Markdown heading blank line. The corrected result guard compares the response UUID to the already validated wire caller and retains the private numeric caller only within Account. R1200 then passes the complete Account unit task (1,783 passed, four existing conditional skips) and all seven native application cases, with enabled affected main/unit/native analysis, formatting and documentation checks passing. Historical R1189 evidence remains attributed to its original response-only source. This focused receiving proof does not establish a published full-service pass, default registration, production custody/PKI or activation. +Temporary preparation in #3359/#3360 may reject parent-issued numeric credentials or non-smoke consumer operations. #2972 owns genuine UUID issuer-to-consumer qualification and restoration of its preserved Profile/internal DTO, native Account and complete transport/item/communication proof postimages. Final supported behavior and retention/security constraints must remain intact. Privileged numeric realm-grant inputs, legacy numeric LogEvent/PlayerReport persistence, numeric deletion-client contracts and the legacy StartSession owner boundary remain separate tracked drift. Full JWT profile/registry qualification, default registration, source custody/PKI, public admission/activation/first OPEN and original NEW recovery holds remain unchanged; Redis absence supplies no provenance. #### Account-owned global REST UUID selectors -The five AccountController account-selector handlers in B’s published REST-only boundary (login-auth-mode GET/PUT, Account export, tenant export, and account DELETE) now accept only canonical lowercase non-nil persisted Account UUIDs. Each resolves the selector through `AccountUuidText` and `AccountService.resolveAccountStorageId(UUID)`, retaining the provenance/source-row guard and using the resulting numeric key only for existing Account-local service calls. The existing numeric `SessionContext` self/global-privileged checks remain on login-auth-mode, Account export, and delete; tenant export retains its numeric tenant selector and existing `requireAccountAccess` behavior. Owner inconsistency or storage failure maps to `AUTH_UNAVAILABLE`. Ordinary control-UI JWT subjects and `accountId` claims remain numeric. The factor-update path still validates the request and checks access before returning its existing `501`; deletion business rules and failure responses are unchanged. - -`AccountControllerTest` now covers UUID owner resolution and the unchanged current-account, global-role, and tenant-access branches; a numeric ordinary JWT still self-binds after UUID resolution. It rejects numeric, malformed, nil, and uppercase selectors on all five handlers before service dispatch, maps inconsistent/unavailable owner resolution to `AUTH_UNAVAILABLE`, and preserves factor-update `501` and role denials. The native Account application test source uses an actual Account-issued ordinary credential to cover self login-mode reads, both export responses and UUID response projections, wrong-owner refusal, invalid-selector refusal, the unchanged factor-update response, and deletion refusal while checking that Account and profile rows remain. The final global REST selector source has complete Account unit execution in R1205 (1,703 passed, four existing conditional skips) and all eight native application cases passing in R1206 with zero failures/errors/skips. Enabled affected main/unit/native analysis, formatting and documentation checks pass in R1206. The unchanged unit postimages retain their R1205 execution attribution; the repeated unit task is up-to-date in R1206. Current published-head full CI and independent review completion remain separate obligations. Controller role claims in unit proof are explicit test inputs, not newly issued roles. - -This local selector transition does not convert ordinary JWT identity, shared authorization, gRPC selector contracts, Logging & Admin deletion callers, or account registration. Canonical tenant-qualified profile routes/authorization, target async and tenant-wide export routes, token-registry behavior, gameplay activation, and production credential custody remain held; Account deletion still retains its existing JOIN receipt, billing-owner, and child-retention denials. +The local final composition validates all five AccountController selectors as canonical persisted UUIDs and binds self/global-role callers before private owner resolution. Tenant export retains its tenant selector and current tenant-access policy. Profile GET/PUT similarly bind the UUID caller before owner SQL, enforce PUT path/body equality and correlate returned Account/tenant identity. Factor-update 501, deletion retention/business-rule denials and unavailable-owner error semantics remain. Canonical tenant-qualified routes, scoped-role/membership-generation qualification and full export lifecycle are separate gaps; representation changes grant no authority. The [Account API](../../architecture/microservices/account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity) owns the contract. -The future local receipt keeps exact UUID caller self/global-role binding and tenant-role authorization, plus its genuine ordinary UUID issuer and internal/gRPC UUID contracts. It receives the strict global REST selectors and bounded owner validation without using B’s historical numeric token comparison. Native requests retain actual private SQL row keys only for persisted Account/profile/provenance assertions; REST selectors and ordinary credentials remain UUIDs. Factor-update `501`, deletion refusal and all policy/production holds remain unchanged. R1204 remains predecessor Account qualification, and R1205/R1206 remain attributed to their B source; this newly received composition is **unrun** pending consolidated inspection and selected proof. +#3356's completed reviews and exact-head CI qualify its narrower response/REST-selector boundary with then-numeric ordinary intake. Its native proof remains attributed to that source. The reconstructed #2972 preserves the final UUID issuer, internal inputs and genuine native credential/HTTP composition; it does not inherit current-code qualification from #3356 or from #3360's controlled preparation callers. Final receiving qualification remains pending, with historical source/proof retained in controller records. #### Social UUID receiver preparation From cfaf49f1206b98b746df8ae8cdb8db0014ec9ce1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:35:13 +1300 Subject: [PATCH 11/34] Retain alias regression with final UUID caller fixture --- .../gamesession/command/text/FriendsCommandHandlerTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 0be4ce9668..018ecb9cc1 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 @@ -1339,7 +1339,7 @@ void friendsVisibilityAcceptsHyphenatedCaseInsensitiveFriendsOnlyAlias() { Mockito.mock(ScriptEventPublisher.class)); when(socialGroupsClient.updateFriendPresencePolicy( 1L, - 41L, + CALLER_ACCOUNT_ID, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_FRIENDS_ONLY)) .thenReturn( @@ -1375,7 +1375,7 @@ void friendsVisibilityAcceptsHyphenatedCaseInsensitiveFriendsOnlyAlias() { Mockito.verify(socialGroupsClient) .updateFriendPresencePolicy( 1L, - 41L, + CALLER_ACCOUNT_ID, net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy .FRIEND_PRESENCE_VISIBILITY_POLICY_FRIENDS_ONLY); } From 7df3268db1a5432ed3ea1b35a27dc64085c1666a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:55:38 +1300 Subject: [PATCH 12/34] Retain the real Social sender-handoff qualification limit --- .../implementation-tracking/player-access-and-session.md | 2 ++ 1 file changed, 2 insertions(+) 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 01e30f1793..cb06f96d92 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -526,6 +526,8 @@ The earlier complete composition has separately attributed proof: R1228 passes 2 Temporary preparation in #3359/#3360 may reject parent-issued numeric credentials or non-smoke consumer operations. #2972 owns genuine UUID issuer-to-consumer qualification and restoration of its preserved Profile/internal DTO, native Account and complete transport/item/communication proof postimages. Final supported behavior and retention/security constraints must remain intact. Privileged numeric realm-grant inputs, legacy numeric LogEvent/PlayerReport persistence, numeric deletion-client contracts and the legacy StartSession owner boundary remain separate tracked drift. Full JWT profile/registry qualification, default registration, source custody/PKI, public admission/activation/first OPEN and original NEW recovery holds remain unchanged; Redis absence supplies no provenance. +The real Game Logic-to-Social `SendMessage` caller still uses workload-only authentication without an authenticated sender binding and therefore fails closed at the strict Social receiver. Controlled `SocialGroupsStubServer` transport cases do not establish real Social acceptance. This remains part of the existing [chat writer authorization and replay gaps](../../architecture/microservices/social-groups-service/api-contracts.md#implementation-status); UUID convergence supplies no internal impersonation grant or player-safe chat claim. + #### Account-owned global REST UUID selectors The local final composition validates all five AccountController selectors as canonical persisted UUIDs and binds self/global-role callers before private owner resolution. Tenant export retains its tenant selector and current tenant-access policy. Profile GET/PUT similarly bind the UUID caller before owner SQL, enforce PUT path/body equality and correlate returned Account/tenant identity. Factor-update 501, deletion retention/business-rule denials and unavailable-owner error semantics remain. Canonical tenant-qualified routes, scoped-role/membership-generation qualification and full export lifecycle are separate gaps; representation changes grant no authority. The [Account API](../../architecture/microservices/account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity) owns the contract. From 714730d64020bcd92e23f1ae705f22c36d44256c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 05:47:55 +1300 Subject: [PATCH 13/34] Retain qualified formatting and correct tracker Markdown --- .../player-access-and-session.md | 2 +- ...leGameplayCommandExecutionServiceTest.java | 32 +++++++++++++++---- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index cb06f96d92..0c7ed70109 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -532,7 +532,7 @@ The real Game Logic-to-Social `SendMessage` caller still uses workload-only auth The local final composition validates all five AccountController selectors as canonical persisted UUIDs and binds self/global-role callers before private owner resolution. Tenant export retains its tenant selector and current tenant-access policy. Profile GET/PUT similarly bind the UUID caller before owner SQL, enforce PUT path/body equality and correlate returned Account/tenant identity. Factor-update 501, deletion retention/business-rule denials and unavailable-owner error semantics remain. Canonical tenant-qualified routes, scoped-role/membership-generation qualification and full export lifecycle are separate gaps; representation changes grant no authority. The [Account API](../../architecture/microservices/account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity) owns the contract. -#3356's completed reviews and exact-head CI qualify its narrower response/REST-selector boundary with then-numeric ordinary intake. Its native proof remains attributed to that source. The reconstructed #2972 preserves the final UUID issuer, internal inputs and genuine native credential/HTTP composition; it does not inherit current-code qualification from #3356 or from #3360's controlled preparation callers. Final receiving qualification remains pending, with historical source/proof retained in controller records. +PR #3356's completed reviews and exact-head CI qualify its narrower response/REST-selector boundary with then-numeric ordinary intake. Its native proof remains attributed to that source. The reconstructed #2972 preserves the final UUID issuer, internal inputs and genuine native credential/HTTP composition; it does not inherit current-code qualification from #3356 or from #3360's controlled preparation callers. Final receiving qualification remains pending, with historical source/proof retained in controller records. #### Social UUID receiver preparation diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java index d4a6fb2655..712ea4c73e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java @@ -346,8 +346,10 @@ void executeStoresAndDeliversRejectedCommunicationAndReplaysItsErrorWithoutReexe .thenReturn(Optional.of(context)); when(durableGameplayReplayService.find(22L, 42L, "tfx-rejected-communication")) .thenReturn(Optional.empty()) - .thenReturn(Optional.of(new DurableGameplayReplayService.ReplayRecord( - false, code, message, java.util.List.of(output)))); + .thenReturn( + Optional.of( + new DurableGameplayReplayService.ReplayRecord( + false, code, message, java.util.List.of(output)))); when(communicationCommandHandler.handle(context, parsed, "tfx-rejected-communication")) .thenReturn( new net.firedevops.firemud.gamesession.command.text.CommunicationCommandHandlingResult( @@ -361,7 +363,14 @@ void executeStoresAndDeliversRejectedCommunicationAndReplaysItsErrorWithoutReexe assertThat(rejected.failureCode()).isEqualTo(code); assertThat(rejected.failureMessage()).isEqualTo(message); verify(durableGameplayReplayService) - .save(22L, 42L, "tfx-rejected-communication", false, code, message, java.util.List.of(output)); + .save( + 22L, + 42L, + "tfx-rejected-communication", + false, + code, + message, + java.util.List.of(output)); verify(playerOutputDeliveryService).deliver(context, java.util.List.of(output), true); DurableGameplayCommandExecutionResult replayed = service.execute(effect, command).orElseThrow(); @@ -372,13 +381,24 @@ void executeStoresAndDeliversRejectedCommunicationAndReplaysItsErrorWithoutReexe assertThat(replayed.failureCode()).isEqualTo(code); assertThat(replayed.failureMessage()).isEqualTo(message); verify(durableGameplayReplayService) - .save(22L, 42L, "tfx-rejected-communication", false, code, message, java.util.List.of(output)); + .save( + 22L, + 42L, + "tfx-rejected-communication", + false, + code, + message, + java.util.List.of(output)); verify(communicationCommandHandler).handle(context, parsed, "tfx-rejected-communication"); verify(playerOutputDeliveryService, Mockito.times(2)) .deliver(context, java.util.List.of(output), true); verify(scriptEventPublisher).publishCommandEvent(context, command); - verifyNoInteractions(itemCommandHandler, moveCommandHandler, afkCommandHandler, - actionStateCommandHandler, movementEffectIdempotencyService); + verifyNoInteractions( + itemCommandHandler, + moveCommandHandler, + afkCommandHandler, + actionStateCommandHandler, + movementEffectIdempotencyService); } @Test From a74fdbf815813a66aecc06a11d559f0a42da559e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 07:11:36 +1300 Subject: [PATCH 14/34] Align smoke Account workload identity and clear image-only build inputs --- dev-tools/tests/compose-grpc-mtls-contract.sh | 15 +++++++------ docker/docker-compose.grpc-mtls.override.yml | 1 + .../docker-compose.smoke-images.override.yml | 22 +++++++++---------- 3 files changed, 20 insertions(+), 18 deletions(-) diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index 7adbef898c..31e5d1ea46 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -499,12 +499,12 @@ for name in app_names: assert mounts[0]["source"] == f"{cert_root}/workloads/{name}", (name, mounts[0]) assert mounts[0].get("read_only") is True, name assert service.get("build") is None, f"image-only proof must not build {name}" -entity_namespace = services["entity-management-service"]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") -assert entity_namespace == "dev", entity_namespace -wms_namespace = services["world-management-service"]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") -assert wms_namespace == "dev", wms_namespace -game_design_namespace = services["game-design-service"]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") -assert game_design_namespace == "dev", game_design_namespace +for name in ( + "account-service", "game-session-service", "entity-management-service", + "world-management-service", "game-design-service", +): + namespace = services[name]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") + assert namespace == "dev", (name, namespace) game_session = services["game-session-service"] game_session_environment = game_session["environment"] assert game_session_environment.get("FIREMUD_SMOKE_RUN_ID") == "" @@ -547,7 +547,8 @@ assert world_management_leaf_mounts[0].get("read_only") is True game_design_receipt_mounts = [mount for mount in game_design.get("volumes", []) if mount.get("target") == source_receipt_dir] assert len(game_design_receipt_mounts) == 1, game_design_receipt_mounts assert game_design_receipt_mounts[0]["source"] == source_receipt_source, game_design_receipt_mounts[0] -assert game_design_receipt_mounts[0].get("read_only") is False +# Compose may omit the default false in rendered JSON; an explicit read-only mount still fails. +assert game_design_receipt_mounts[0].get("read_only", False) is False world_management = services["world-management-service"] world_management_environment = world_management["environment"] assert world_management_environment.get("FIREMUD_SMOKE_RUN_ID") == "" diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index 6b4db45411..f293082502 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -16,6 +16,7 @@ services: account-service: environment: <<: *grpc-mtls-environment + FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/account-service:/app/certs:ro diff --git a/docker/docker-compose.smoke-images.override.yml b/docker/docker-compose.smoke-images.override.yml index dbb25375aa..d3f976fff3 100644 --- a/docker/docker-compose.smoke-images.override.yml +++ b/docker/docker-compose.smoke-images.override.yml @@ -1,55 +1,55 @@ services: account-service: - build: null + build: !reset null image: ghcr.io/benhook1013/account-service:${SMOKE_IMAGE_TAG} pull_policy: ${SMOKE_IMAGE_PULL_POLICY:-always} automation-scripting-service: - build: null + build: !reset null image: ghcr.io/benhook1013/automation-scripting-service:${SMOKE_IMAGE_TAG} pull_policy: ${SMOKE_IMAGE_PULL_POLICY:-always} entity-management-service: - build: null + build: !reset null image: ghcr.io/benhook1013/entity-management-service:${SMOKE_IMAGE_TAG} pull_policy: ${SMOKE_IMAGE_PULL_POLICY:-always} game-design-service: - build: null + build: !reset null image: ghcr.io/benhook1013/game-design-service:${SMOKE_IMAGE_TAG} pull_policy: ${SMOKE_IMAGE_PULL_POLICY:-always} game-logic-service: - build: null + build: !reset null image: ghcr.io/benhook1013/game-logic-service:${SMOKE_IMAGE_TAG} pull_policy: ${SMOKE_IMAGE_PULL_POLICY:-always} game-session-service: - build: null + build: !reset null image: ghcr.io/benhook1013/game-session-service:${SMOKE_IMAGE_TAG} pull_policy: ${SMOKE_IMAGE_PULL_POLICY:-always} logging-admin-service: - build: null + build: !reset null image: ghcr.io/benhook1013/logging-admin-service:${SMOKE_IMAGE_TAG} pull_policy: ${SMOKE_IMAGE_PULL_POLICY:-always} social-groups-service: - build: null + build: !reset null image: ghcr.io/benhook1013/social-groups-service:${SMOKE_IMAGE_TAG} pull_policy: ${SMOKE_IMAGE_PULL_POLICY:-always} gateway: - build: null + build: !reset null image: ghcr.io/benhook1013/spring-cloud-gateway:${SMOKE_IMAGE_TAG} pull_policy: ${SMOKE_IMAGE_PULL_POLICY:-always} tcp-proxy-service: - build: null + build: !reset null image: ghcr.io/benhook1013/tcp-proxy-service:${SMOKE_IMAGE_TAG} pull_policy: ${SMOKE_IMAGE_PULL_POLICY:-always} world-management-service: - build: null + build: !reset null image: ghcr.io/benhook1013/world-management-service:${SMOKE_IMAGE_TAG} pull_policy: ${SMOKE_IMAGE_PULL_POLICY:-always} From 242786cb793f2ad77b81b80f4cf1bd55813336be Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 08:08:20 +1300 Subject: [PATCH 15/34] Complete ordinary Entity Account UUID receiving and authenticated demo seeding --- .../api-contracts.md | 6 ++ .../runtime-and-data.md | 3 + design/grpc-docs/grpc-api.md | 6 +- .../gameplay-rules-entities-and-effects.md | 6 ++ docker/docker-compose.grpc-mtls.override.yml | 3 + .../v1/entity_management_service.proto | 3 + .../DemoAccountAuthenticationClient.java | 97 +++++++++++++++++ .../EntityManagementRequestReaders.java | 7 +- .../entitymanagement/data/TestDataSeeder.java | 15 ++- .../entitymanagement/dto/CharacterDto.java | 11 +- .../entitymanagement/entity/Character.java | 28 +++++ .../entity/CharacterEquipmentEntry.java | 2 + .../entity/ContainerInstance.java | 2 + .../entity/InventoryEntry.java | 2 + .../mapper/CharacterMapper.java | 3 + .../CharacterEquipmentRepository.java | 2 + .../repository/CharacterRepository.java | 7 +- .../ContainerInstanceRepository.java | 2 + .../repository/InventoryEntryRepository.java | 2 + .../repository/ItemInstanceRepository.java | 4 + .../repository/ItemStackRepository.java | 4 + ...JooqEntityManagementRepositorySupport.java | 8 +- .../service/CharacterService.java | 4 +- .../service/impl/CharacterServiceImpl.java | 14 ++- .../impl/EntityManagementGrpcService.java | 8 +- .../src/main/resources/application.yml | 1 + .../V1024__ordinary_account_uuid_owner.sql | 7 ++ ...countUuidOwnerPostgresIntegrationTest.java | 100 ++++++++++++++++++ ...eseededActorAssignmentIntegrationTest.java | 8 +- .../RetainedActorIdentityIntegrationTest.java | 19 ++-- .../DemoAccountAuthenticationClientTest.java | 93 ++++++++++++++++ .../controller/CharacterControllerTest.java | 12 ++- .../data/TestDataSeederTest.java | 37 +++++++ .../impl/CharacterServiceImplListTest.java | 21 ++-- .../impl/CharacterServiceImplTest.java | 2 + .../impl/EntityManagementGrpcServiceTest.java | 70 ++++++++---- 36 files changed, 555 insertions(+), 64 deletions(-) create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClient.java create mode 100644 services/entity-management-service/src/main/resources/db/migration/V1024__ordinary_account_uuid_owner.sql create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 2e1a8877c2..b9c83cb759 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -4,6 +4,12 @@ This document defines the Entity Management REST and gRPC surfaces, design-time The authoritative REST schema source lives in [../../../../services/entity-management-service/src/main/resources/openapi.yaml](../../../../services/entity-management-service/src/main/resources/openapi.yaml). Proto definitions are the authoritative gRPC source. +## Ordinary Account ownership + +Ordinary character request/response Account identities use canonical lowercase non-nil Account UUIDs under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) and the [Account identity contract](../account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity). Entity persists this owner in the existing `characters.account_uuid` column. Numeric `characters.account_id` is retained source-row evidence only, never a public selector or response identity; numeric wire fallback and inferred UUID mappings are not supported. + +Ordinary roster predicates retain their existing tenant/playable-state boundary and require an exact UUID owner. Rows without UUID ownership remain retained but are absent from UUID-selected rosters. Account UUID ownership alone does not establish canonical tenant, namespace, actor assignment, `OWNER_RESOLVED`, created-origin, admission or activation authority. The existing canonical provenance predicates and registration holds below remain in force. The scalar `CreateCharacter` RPC remains unavailable pending its owner protections. + ## Implementation Status The [protected preseeded assignment ingress](#protected-preseeded-actor-assignment) and its Game Session client are manually composed and unregistered. Their current proof and remaining execution gaps are recorded in the [assignment tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#protected-preseeded-assignment-ingress). diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 766aab7ea8..8ce24daa02 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -4,6 +4,9 @@ This document defines Entity Management’s runtime model, persistence ownership ## Implementation Status +- Ordinary Account ownership uses the existing `characters.account_uuid` carrier; V1024 permits fresh ordinary rows without fabricated numeric source evidence and adds an ordinary UUID roster index. It leaves retained numeric/unresolved rows unchanged and does not promote canonical actor provenance. Representation and admission consequences belong to [API Contracts](./api-contracts.md#ordinary-account-ownership); implementation/proof status belongs to the [Entity tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#ordinary-account-uuid-ownership). +- Explicit local demo seeding authenticates the actual demo credentials through the normal Account mTLS `Authenticate` API and takes its canonical UUID response. It fails on unavailable identity or a retained demo character with missing/different UUID ownership, without repairing ownership by name or numeric row. The mTLS Compose profile starts Entity after Account health. This fixture operation grants no production registration, creation or admission authority. + - The current crafting REST adapter is runtime-reachable legacy implementation drift, not a supported or advertised boundary: the crafting paths and schemas are omitted from the ping-only authoritative OpenAPI, whose root `security: []` applies only to the health contract, so the adapter remains unsupported/nonconformant. The deployed interceptor requires any `AUTHENTICATED` bearer because this non-public path is not in the public-route list, but neither layer provides tenant binding; there is no controller `SessionContext` tenant guard. `CraftingServiceImpl` trusts the DTO's `tenantId`, `resultItemId`, and ingredient item IDs; `CraftingRecipeRepository.findWithIngredientsById` and the update branch use recipe ID alone, while ingredient loading also uses recipe ID alone. The tenant-qualified list methods first select IDs but then re-enter that unqualified lookup, so they are not evidence of an end-to-end tenant predicate. Existing crafting tests do not establish caller-tenant authorization, cross-tenant recipe isolation, or same-tenant result/ingredient ownership. - World owns guarded, manually composed initial `character_location` storage and its unregistered placement/read boundary. General movement, occupancy and NPC location remain unqualified; `room_instance` is topology, and a Game Session room binding is not World location authority. Entity Management must not add competing location persistence or treat a cache/projection as authoritative. - **Target crafting boundary:** require authenticated caller context and exact tenant authorization before any recipe operation, derive the target tenant rather than treating request `tenantId` as authority, and make recipe read/update and ingredient load/update predicates tenant-qualified. Validate that the result item and every ingredient item belong to the target tenant and the same applicable version/Draft scope before writing. A missing context, tenant mismatch, recipe mismatch, or cross-tenant item reference fails closed before any recipe or ingredient mutation; the target negative proof must exercise each case. diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index 185f6c15ec..668096ab03 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -7660,7 +7660,7 @@ Immutable identity and content digest of one exact roster snapshot. | ----- | ---- | ----- | ----------- | | id | [string](#string) | | | | tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | +| account_id | [string](#string) | | Canonical lowercase non-nil Account UUID ownership. | | name | [string](#string) | | | | level | [int32](#int32) | | | | experience | [int32](#int32) | | | @@ -7745,7 +7745,7 @@ Immutable identity and content digest of one exact roster snapshot. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | +| account_id | [string](#string) | | Canonical lowercase non-nil Account UUID; never an Account private row key. | | name | [string](#string) | | | | game_instance_id | [string](#string) | | | | playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | @@ -7945,7 +7945,7 @@ Immutable identity and content digest of one exact roster snapshot. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | +| account_id | [string](#string) | | Canonical lowercase non-nil Account UUID; never an Account private row key. | | game_instance_id | [string](#string) | | | | playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 4efbd39429..af5a6de3dc 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -247,6 +247,12 @@ The fourth CLI correction isolates all Entity sweep stages, keeps failed-page cu The next review correction at code checkpoint `ce02d51f608f199e531de32c1d15f63cbaae77cb` guards Game Session blocking-health reads, reports unavailable values as `-1` with a fixed `health_failure` counter, preserves malformed-caller versus invalid-owner/stored-receipt recovery classifications, and maps only the exact original-source mismatch to stale-authority status. Entity checks its locked unbound admission's own elapsed closure horizon before exposing a durable retirement transfer; purge and transfer insertion remain atomic. R58 freshly passes all 370 Entity unit cases, 2,492 Game Session unit cases, 69 Entity PostgreSQL cases, 357 Game Session PostgreSQL cases and 36 cross-service cases. After the third hosted corrections, R60 freshly passes 370 Entity unit cases, 2,494 Game Session unit cases and all 18 retention PostgreSQL cases, including no early transfer, transaction rollback and exact later transfer. R61 passes affected formatting, Checkstyle and SpotBugs. Controlled mTLS proof exercises the actual current-source owner comparison and the Entity recovery client/handler boundary; storage and upstream owner doubles remain explicitly limited. Normal reconciliation to the actual merged fixture parent produces `3cab778681f960d97abb5f4d2439edd6d30d8ab1` with the identical complete code tree. R59 rebuilds fresh images at that reconciled checkpoint and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`. Authenticated teardown completes, and independent exact-project checks confirm no remaining containers, networks or volumes. This does not establish genuine source custody, registration, activation or public admission. +### Ordinary Account UUID ownership + +The local ordinary receiving boundary uses the existing persisted Account UUID for character DTOs, strict wire readers, roster/name projections, service inputs and nested character copies. Numeric Account source-row evidence remains retained and is excluded from public identity. Forward V1024 changes nullability/indexing without mapping or rewriting retained ownership. Explicit demo seeding obtains the owner from real Account credential authentication and refuses missing/mismatched retained ownership. The [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#ordinary-account-ownership) owns the contract. + +Focused authored proof covers canonical UUID projection and tenant/owner isolation, preserved numeric-source rows, migration history, nil rejection, missing/mismatched seed-owner refusal and actual authentication-response validation with controlled collaborators. The authorized Entity formatting/main/unit/native compilation selection passes after two old numeric roster fixture calls were corrected; its first failed native compilation and successful recovery remain separately retained. These are compilation results, not test execution. Unit/native execution, actual mTLS seed authentication and fresh-image LOGIN/PLAY/LOOK remain pending Root's consolidated qualification. Existing canonical actor/created-origin provenance, unregistered owner machinery, production custody, admission and activation holds remain unchanged. + ## Active Gaps - The initial runtime projection has one retained Entity allocator, but legacy character, NPC and container allocation paths have not converged onto it. Their numeric row IDs are not interchangeable with the purpose-specific owner-qualified runtime reference. Unified producer allocation and generic actor lookup remain unimplemented; the [Entity runtime identity owner](../../architecture/microservices/entity-management-service/runtime-and-data.md#runtime-actor-identity) defines the target precondition. diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index f293082502..fe093dae93 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -36,6 +36,9 @@ services: environment: <<: *grpc-mtls-environment FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev + depends_on: + account-service: + condition: service_healthy volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/entity-management-service:/app/certs:ro diff --git a/protos/entity-management/v1/entity_management_service.proto b/protos/entity-management/v1/entity_management_service.proto index d84b267aa7..1cd5e858d6 100644 --- a/protos/entity-management/v1/entity_management_service.proto +++ b/protos/entity-management/v1/entity_management_service.proto @@ -218,6 +218,7 @@ enum CanonicalGameplayRosterActorKind { message CreateCharacterRequest { string tenant_id = 1; + // Canonical lowercase non-nil Account UUID; never an Account private row key. string account_id = 2; string name = 3; string game_instance_id = 4; @@ -459,6 +460,7 @@ enum PlayableStateScope { message ListCharactersByAccountRequest { string tenant_id = 1; + // Canonical lowercase non-nil Account UUID; never an Account private row key. string account_id = 2; string game_instance_id = 3; PlayableStateScope playable_state_scope = 4; @@ -467,6 +469,7 @@ message ListCharactersByAccountRequest { message Character { string id = 1; string tenant_id = 2; + // Canonical lowercase non-nil Account UUID ownership. string account_id = 3; string name = 4; int32 level = 5; diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClient.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClient.java new file mode 100644 index 0000000000..7495100334 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClient.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.entitymanagement.client; + +import io.grpc.ManagedChannel; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; +import java.io.IOException; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.security.JwtClaims; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; + +/** Ordinary credential authentication used only by explicitly enabled local demo seeding. */ +@Component +@ConditionalOnProperty( + prefix = "firemud.smoke.seed-demo-runtime", + name = "enabled", + havingValue = "true") +public final class DemoAccountAuthenticationClient + extends AbstractReloadingBlockingGrpcClient { + private final String namespace; + private final String email; + private final String password; + + public DemoAccountAuthenticationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channelFactory, + @Value("${firemud.grpc.workload-namespace:}") String namespace, + @Value("${firemud.smoke.seed-demo-account.email:demo@example.com}") String email, + @Value("${firemud.smoke.seed-demo-account.password:swordfish}") String password) { + super( + endpoints, + EntityManagementSourceClientValidation.requireEntityManagementMtls( + tls, "Demo Account authentication"), + channelFactory, + DemoAccountAuthenticationClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException( + "Demo authentication requires the configured workload namespace"); + } + this.namespace = namespace; + this.email = email; + this.password = password; + } + + @PostConstruct + public void init() throws IOException { + initOnce("Demo Account client is closed", "Demo Account client is not initialized"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountServiceGrpc.AccountServiceBlockingStub buildStub(ManagedChannel channel) { + return AccountServiceGrpc.newBlockingStub(channel) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + namespace + "/sa/account-service")); + } + + public UUID authenticateDemoOwner() { + var response = + requireInitializedStub("Demo Account client is not initialized") + .withDeadlineAfter(5, TimeUnit.SECONDS) + .authenticate( + AuthenticateRequest.newBuilder().setEmail(email).setPassword(password).build()); + if (response.hasError() || response.getAuthToken().isBlank()) { + throw new IllegalStateException("Account demo authentication is unavailable"); + } + return UUID.fromString( + JwtClaims.requireCanonicalAccountUuid(response.getAccountId(), "accountId")); + } + + @Override + @PreDestroy + public void close() throws IOException { + super.close(); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EntityManagementRequestReaders.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EntityManagementRequestReaders.java index 09937e98ef..959f9523b5 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EntityManagementRequestReaders.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EntityManagementRequestReaders.java @@ -16,7 +16,10 @@ static long requirePositivePathId(String value, String fieldName) { static AccountScope requireAccountScope(String tenantId, String accountId) { return new AccountScope( - requirePositivePathId(tenantId, "tenantId"), requirePositivePathId(accountId, "accountId")); + requirePositivePathId(tenantId, "tenantId"), + java.util.UUID.fromString( + net.firedevops.firemud.common.security.JwtClaims.requireCanonicalAccountUuid( + accountId, "accountId"))); } static CharacterScope requireCharacterScope(String tenantId, String characterId) { @@ -35,7 +38,7 @@ static ResponseEntity> withBadRequest( } } - record AccountScope(long tenantId, long accountId) {} + record AccountScope(long tenantId, java.util.UUID accountId) {} record CharacterScope(long tenantId, long characterId) {} } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/data/TestDataSeeder.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/data/TestDataSeeder.java index 0d4fd65211..e83cae5435 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/data/TestDataSeeder.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/data/TestDataSeeder.java @@ -29,7 +29,8 @@ @RequiredArgsConstructor public class TestDataSeeder implements ApplicationRunner { private static final long DEMO_TENANT_ID = 1L; - private static final long DEMO_ACCOUNT_ID = 1L; + private final net.firedevops.firemud.entitymanagement.client.DemoAccountAuthenticationClient + demoAccountAuthenticationClient; private static final long VERSION_ID = 1L; private static final String SHARED_LIVE_PLAYABLE_STATE = "shared-live"; private static final String DEMO_CHARACTER_NAME = "demo"; @@ -46,7 +47,8 @@ public class TestDataSeeder implements ApplicationRunner { @Override @Transactional public void run(ApplicationArguments args) { - Character demo = ensureDemoCharacter(); + java.util.UUID accountUuid = demoAccountAuthenticationClient.authenticateDemoOwner(); + Character demo = ensureDemoCharacter(accountUuid); ensureEquipmentSchema(); Item torch = ensureItem("Torch", "A small torch", null); Item backpack = ensureItem("Backpack", "A weathered backpack", "BACK"); @@ -63,13 +65,16 @@ public void run(ApplicationArguments args) { ensureCarriedItem(demo, ironBoots, "boots", 1L, "boots#1"); } - private Character ensureDemoCharacter() { + private Character ensureDemoCharacter(java.util.UUID accountUuid) { return characterRepository .findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( DEMO_TENANT_ID, SHARED_LIVE_PLAYABLE_STATE, DEMO_CHARACTER_NAME) .map( character -> { - character.setAccountId(DEMO_ACCOUNT_ID); + if (!accountUuid.equals(character.getAccountUuid())) { + throw new IllegalStateException( + "Retained demo character has unresolved or different Account ownership"); + } character.setBodyLayoutKey("DEFAULT"); return characterRepository.save(character); }) @@ -77,7 +82,7 @@ private Character ensureDemoCharacter() { () -> { Character character = new Character(); character.setTenantId(DEMO_TENANT_ID); - character.setAccountId(DEMO_ACCOUNT_ID); + character.setAccountUuid(accountUuid); character.setPlayableStateKey(SHARED_LIVE_PLAYABLE_STATE); character.setName(DEMO_CHARACTER_NAME); character.setBodyLayoutKey("DEFAULT"); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/dto/CharacterDto.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/dto/CharacterDto.java index f973f94fbc..afcea6a0ae 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/dto/CharacterDto.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/dto/CharacterDto.java @@ -7,7 +7,7 @@ public record CharacterDto( Long id, @NotNull Long tenantId, - @NotNull Long accountId, + @NotNull java.util.UUID accountId, @NotNull @Size(max = 100) String name, @NotNull PlayableStateScope playableStateScope, int level, @@ -17,4 +17,11 @@ public record CharacterDto( int intelligence, int stamina, int health, - int mana) {} + int mana) { + public CharacterDto { + if (accountId == null || accountId.equals(new java.util.UUID(0L, 0L))) { + throw new IllegalArgumentException( + "Public character ownership requires a non-nil Account UUID"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java index 9056764770..bd6a455c71 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java @@ -13,7 +13,35 @@ public class Character { @EqualsAndHashCode.Include private Long id; private ActorIdentity actorIdentity; private Long tenantId; + + /** Retained private source-row evidence; never a public Account selector. */ private Long accountId; + + private java.util.UUID accountUuid; + + public void setAccountUuid(java.util.UUID value) { + if (value != null && value.equals(new java.util.UUID(0L, 0L))) { + throw new IllegalArgumentException("Account UUID must not be nil"); + } + if (value != null + && actorIdentity != null + && actorIdentity.accountUuid() != null + && !value.equals(actorIdentity.accountUuid())) { + throw new IllegalArgumentException("Account owner conflicts with actor identity"); + } + accountUuid = value; + } + + public void setActorIdentity(ActorIdentity value) { + if (value != null + && accountUuid != null + && value.accountUuid() != null + && !accountUuid.equals(value.accountUuid())) { + throw new IllegalArgumentException("Actor identity conflicts with Account owner"); + } + actorIdentity = value; + } + private String playableStateKey; private String name; private String bodyLayoutKey = "DEFAULT"; diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/CharacterEquipmentEntry.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/CharacterEquipmentEntry.java index 993ed5c1de..0f5e8d99b6 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/CharacterEquipmentEntry.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/CharacterEquipmentEntry.java @@ -45,6 +45,7 @@ public Character getCharacter() { copy.setId(character.getId()); copy.setTenantId(character.getTenantId()); copy.setAccountId(character.getAccountId()); + copy.setAccountUuid(character.getAccountUuid()); copy.setName(character.getName()); return copy; } @@ -57,6 +58,7 @@ public void setCharacter(Character character) { copy.setId(character.getId()); copy.setTenantId(character.getTenantId()); copy.setAccountId(character.getAccountId()); + copy.setAccountUuid(character.getAccountUuid()); copy.setName(character.getName()); this.character = copy; } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ContainerInstance.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ContainerInstance.java index ce9816ca4e..8005c0eff5 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ContainerInstance.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ContainerInstance.java @@ -23,6 +23,7 @@ public Character getCharacter() { copy.setId(character.getId()); copy.setTenantId(character.getTenantId()); copy.setAccountId(character.getAccountId()); + copy.setAccountUuid(character.getAccountUuid()); copy.setName(character.getName()); return copy; } @@ -35,6 +36,7 @@ public void setCharacter(Character character) { copy.setId(character.getId()); copy.setTenantId(character.getTenantId()); copy.setAccountId(character.getAccountId()); + copy.setAccountUuid(character.getAccountUuid()); copy.setName(character.getName()); this.character = copy; } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/InventoryEntry.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/InventoryEntry.java index c7ed9177e7..29e553fd3d 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/InventoryEntry.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/InventoryEntry.java @@ -46,6 +46,7 @@ public Character getCharacter() { copy.setId(character.getId()); copy.setTenantId(character.getTenantId()); copy.setAccountId(character.getAccountId()); + copy.setAccountUuid(character.getAccountUuid()); copy.setName(character.getName()); return copy; } @@ -58,6 +59,7 @@ public void setCharacter(Character character) { copy.setId(character.getId()); copy.setTenantId(character.getTenantId()); copy.setAccountId(character.getAccountId()); + copy.setAccountUuid(character.getAccountUuid()); copy.setName(character.getName()); this.character = copy; } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java index 4187236beb..d8a3551a0b 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java @@ -8,6 +8,7 @@ @Mapper(componentModel = "spring") public interface CharacterMapper { @Mapping(target = "playableStateScope", ignore = true) + @Mapping(target = "accountId", source = "accountUuid") CharacterDto toDto(Character entity); @Mapping(target = "inventoryEntries", ignore = true) @@ -16,5 +17,7 @@ public interface CharacterMapper { @Mapping(target = "bodyLayoutKey", constant = "DEFAULT") @Mapping(target = "actorIdentity", ignore = true) @Mapping(target = "version", ignore = true) + @Mapping(target = "accountUuid", source = "accountId") + @Mapping(target = "accountId", ignore = true) Character toEntity(CharacterDto dto); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java index 6d7c2e5470..2fe5a48f00 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java @@ -46,6 +46,7 @@ public Page findByIdCharacterIdAndCharacterTenantId( CHARACTERS.ID, CHARACTERS.TENANT_ID, CHARACTERS.ACCOUNT_ID, + CHARACTERS.ACCOUNT_UUID, CHARACTERS.PLAYABLE_STATE_KEY, CHARACTERS.NAME, ITEMS.ID, @@ -97,6 +98,7 @@ private CharacterEquipmentEntry toEntity(Record record) { record.get(CHARACTERS.ID), record.get(CHARACTERS.TENANT_ID), record.get(CHARACTERS.ACCOUNT_ID), + record.get(CHARACTERS.ACCOUNT_UUID), record.get(CHARACTERS.PLAYABLE_STATE_KEY), record.get(CHARACTERS.NAME)), JooqEntityManagementRepositorySupport.partialItem( diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java index 6b099f1b0a..71e5eeb6c8 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java @@ -235,12 +235,12 @@ public Optional findByIdAndTenantIdAndPlayableStateKey( } public Page findByTenantIdAndAccountIdAndPlayableStateKey( - Long tenantId, Long accountId, String playableStateKey, Pageable pageable) { + Long tenantId, UUID accountId, String playableStateKey, Pageable pageable) { var condition = CHARACTERS .TENANT_ID .eq(tenantId) - .and(CHARACTERS.ACCOUNT_ID.eq(accountId)) + .and(CHARACTERS.ACCOUNT_UUID.eq(accountId)) .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey)) .and(legacyCharacterRow()); long total = dsl.fetchCount(CHARACTERS, condition); @@ -1376,6 +1376,7 @@ public Character save(Character entity) { .set(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON, "OWNER_PROVENANCE_MISSING") .set(CHARACTERS.TENANT_ID, entity.getTenantId()) .set(CHARACTERS.ACCOUNT_ID, entity.getAccountId()) + .set(CHARACTERS.ACCOUNT_UUID, entity.getAccountUuid()) .set(CHARACTERS.PLAYABLE_STATE_KEY, entity.getPlayableStateKey()) .set(CHARACTERS.NAME, entity.getName()) .set(CHARACTERS.BODY_LAYOUT_KEY, entity.getBodyLayoutKey()) @@ -1396,6 +1397,7 @@ public Character save(Character entity) { dsl.update(CHARACTERS) .set(CHARACTERS.TENANT_ID, entity.getTenantId()) .set(CHARACTERS.ACCOUNT_ID, entity.getAccountId()) + .set(CHARACTERS.ACCOUNT_UUID, entity.getAccountUuid()) .set(CHARACTERS.PLAYABLE_STATE_KEY, entity.getPlayableStateKey()) .set(CHARACTERS.NAME, entity.getName()) .set(CHARACTERS.BODY_LAYOUT_KEY, entity.getBodyLayoutKey()) @@ -1433,6 +1435,7 @@ private Character toEntity(Record record) { record.get(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON))); character.setTenantId(record.get(CHARACTERS.TENANT_ID)); character.setAccountId(record.get(CHARACTERS.ACCOUNT_ID)); + character.setAccountUuid(record.get(CHARACTERS.ACCOUNT_UUID)); character.setPlayableStateKey(record.get(CHARACTERS.PLAYABLE_STATE_KEY)); character.setName(record.get(CHARACTERS.NAME)); character.setBodyLayoutKey(record.get(CHARACTERS.BODY_LAYOUT_KEY)); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ContainerInstanceRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ContainerInstanceRepository.java index 2a544ec9df..6d11bba689 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ContainerInstanceRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ContainerInstanceRepository.java @@ -181,6 +181,7 @@ private SelectConditionStep baseSelect(Condition condition) { holderCharactersTable.field("id", Long.class), holderCharactersTable.field("tenant_id", Long.class), holderCharactersTable.field("account_id", Long.class), + holderCharactersTable.field("account_uuid", java.util.UUID.class), holderCharactersTable.field("playable_state_key", String.class), holderCharactersTable.field("name", String.class), ITEMS.ID, @@ -215,6 +216,7 @@ private ContainerInstance toEntity(Record record) { record.get(holderCharactersTable.field("id", Long.class)), record.get(holderCharactersTable.field("tenant_id", Long.class)), record.get(holderCharactersTable.field("account_id", Long.class)), + record.get(holderCharactersTable.field("account_uuid", java.util.UUID.class)), record.get(holderCharactersTable.field("playable_state_key", String.class)), record.get(holderCharactersTable.field("name", String.class))), record.get(CONTAINER_INSTANCES.EQUIPMENT_SLOT), diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/InventoryEntryRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/InventoryEntryRepository.java index c6662bf066..1d45018703 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/InventoryEntryRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/InventoryEntryRepository.java @@ -62,6 +62,7 @@ private Page fetchPage(Condition condition, Pageable pageable) { CHARACTERS.ID, CHARACTERS.TENANT_ID, CHARACTERS.ACCOUNT_ID, + CHARACTERS.ACCOUNT_UUID, CHARACTERS.PLAYABLE_STATE_KEY, CHARACTERS.NAME, ITEMS.ID, @@ -98,6 +99,7 @@ private InventoryEntry toEntity(Record record) { record.get(CHARACTERS.ID), record.get(CHARACTERS.TENANT_ID), record.get(CHARACTERS.ACCOUNT_ID), + record.get(CHARACTERS.ACCOUNT_UUID), record.get(CHARACTERS.PLAYABLE_STATE_KEY), record.get(CHARACTERS.NAME)), JooqEntityManagementRepositorySupport.partialItem( diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ItemInstanceRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ItemInstanceRepository.java index fb57230297..e2644bd89c 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ItemInstanceRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ItemInstanceRepository.java @@ -293,6 +293,7 @@ private SelectConditionStep baseSelect(Condition condition) { holderCharactersTable.field("id", Long.class), holderCharactersTable.field("tenant_id", Long.class), holderCharactersTable.field("account_id", Long.class), + holderCharactersTable.field("account_uuid", java.util.UUID.class), holderCharactersTable.field("playable_state_key", String.class), holderCharactersTable.field("name", String.class), ITEMS.ID, @@ -316,6 +317,7 @@ private SelectConditionStep baseSelect(Condition condition) { containerCharactersTable.field("id", Long.class), containerCharactersTable.field("tenant_id", Long.class), containerCharactersTable.field("account_id", Long.class), + containerCharactersTable.field("account_uuid", java.util.UUID.class), containerCharactersTable.field("playable_state_key", String.class), containerCharactersTable.field("name", String.class)) .from(ITEM_INSTANCES) @@ -343,6 +345,7 @@ private ItemInstance toEntity(Record record) { record.get(holderCharactersTable.field("id", Long.class)), record.get(holderCharactersTable.field("tenant_id", Long.class)), record.get(holderCharactersTable.field("account_id", Long.class)), + record.get(holderCharactersTable.field("account_uuid", java.util.UUID.class)), record.get(holderCharactersTable.field("playable_state_key", String.class)), record.get(holderCharactersTable.field("name", String.class))), record.get(ITEM_INSTANCES.EQUIPMENT_SLOT), @@ -355,6 +358,7 @@ private ItemInstance toEntity(Record record) { record.get(containerCharactersTable.field("id", Long.class)), record.get(containerCharactersTable.field("tenant_id", Long.class)), record.get(containerCharactersTable.field("account_id", Long.class)), + record.get(containerCharactersTable.field("account_uuid", java.util.UUID.class)), record.get(containerCharactersTable.field("playable_state_key", String.class)), record.get(containerCharactersTable.field("name", String.class))), record.get(CONTAINER_INSTANCES.EQUIPMENT_SLOT), diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ItemStackRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ItemStackRepository.java index e63ff28acb..5a4cc85d35 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ItemStackRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ItemStackRepository.java @@ -270,6 +270,7 @@ private SelectConditionStep baseSelect(Condition condition) { holderCharactersTable.field("id", Long.class), holderCharactersTable.field("tenant_id", Long.class), holderCharactersTable.field("account_id", Long.class), + holderCharactersTable.field("account_uuid", java.util.UUID.class), holderCharactersTable.field("playable_state_key", String.class), holderCharactersTable.field("name", String.class), ITEMS.ID, @@ -293,6 +294,7 @@ private SelectConditionStep baseSelect(Condition condition) { containerCharactersTable.field("id", Long.class), containerCharactersTable.field("tenant_id", Long.class), containerCharactersTable.field("account_id", Long.class), + containerCharactersTable.field("account_uuid", java.util.UUID.class), containerCharactersTable.field("playable_state_key", String.class), containerCharactersTable.field("name", String.class)) .from(ITEM_STACKS) @@ -320,6 +322,7 @@ private ItemStack toEntity(Record record) { record.get(holderCharactersTable.field("id", Long.class)), record.get(holderCharactersTable.field("tenant_id", Long.class)), record.get(holderCharactersTable.field("account_id", Long.class)), + record.get(holderCharactersTable.field("account_uuid", java.util.UUID.class)), record.get(holderCharactersTable.field("playable_state_key", String.class)), record.get(holderCharactersTable.field("name", String.class))), record.get(ITEM_STACKS.EQUIPMENT_SLOT), @@ -332,6 +335,7 @@ private ItemStack toEntity(Record record) { record.get(containerCharactersTable.field("id", Long.class)), record.get(containerCharactersTable.field("tenant_id", Long.class)), record.get(containerCharactersTable.field("account_id", Long.class)), + record.get(containerCharactersTable.field("account_uuid", java.util.UUID.class)), record.get(containerCharactersTable.field("playable_state_key", String.class)), record.get(containerCharactersTable.field("name", String.class))), record.get(CONTAINER_INSTANCES.EQUIPMENT_SLOT), diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/JooqEntityManagementRepositorySupport.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/JooqEntityManagementRepositorySupport.java index 9a780b595c..fa28ef4e50 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/JooqEntityManagementRepositorySupport.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/JooqEntityManagementRepositorySupport.java @@ -37,7 +37,12 @@ static int offsetOrZero(Pageable pageable) { } static Character partialCharacter( - Long id, Long tenantId, Long accountId, String playableStateKey, String name) { + Long id, + Long tenantId, + Long accountId, + java.util.UUID accountUuid, + String playableStateKey, + String name) { if (id == null) { return null; } @@ -45,6 +50,7 @@ static Character partialCharacter( character.setId(id); character.setTenantId(tenantId); character.setAccountId(accountId); + character.setAccountUuid(accountUuid); character.setPlayableStateKey(playableStateKey); character.setName(name); return character; diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CharacterService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CharacterService.java index 24e0ea9355..fb969a40a9 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CharacterService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CharacterService.java @@ -12,7 +12,7 @@ public interface CharacterService { /** Creates a new character with default stats. */ CharacterDto create( Long tenantId, - Long accountId, + java.util.UUID accountId, String name, String gameInstanceId, PlayableStateScope playableStateScope); @@ -34,7 +34,7 @@ boolean updateEntity( /** Lists all characters visible for one resolved gameplay target. */ Page listForGameplayScope( Long tenantId, - Long accountId, + java.util.UUID accountId, String gameInstanceId, PlayableStateScope playableStateScope, Pageable pageable); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java index a6ec5bb285..adcfb9ed65 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java @@ -51,13 +51,14 @@ void initMetrics() { @Timed(value = "character.create") public CharacterDto create( Long tenantId, - Long accountId, + java.util.UUID accountId, String name, String gameInstanceId, PlayableStateScope playableStateScope) { + requireAccountOwner(accountId); Character entity = new Character(); entity.setTenantId(tenantId); - entity.setAccountId(accountId); + entity.setAccountUuid(accountId); entity.setName(name); entity.setPlayableStateKey( playableStateKeyResolver.resolve(gameInstanceId, playableStateScope)); @@ -136,10 +137,11 @@ public boolean updateEntity( @Timed(value = "character.listForAccount") public Page listForGameplayScope( Long tenantId, - Long accountId, + java.util.UUID accountId, String gameInstanceId, PlayableStateScope playableStateScope, Pageable pageable) { + requireAccountOwner(accountId); return characterRepository .findByTenantIdAndAccountIdAndPlayableStateKey( tenantId, @@ -165,6 +167,12 @@ public java.util.Optional findByGameplayScopeAndName( .map(this::toDto); } + private static void requireAccountOwner(java.util.UUID accountId) { + if (accountId == null || accountId.equals(new java.util.UUID(0L, 0L))) { + throw new IllegalArgumentException("A non-nil Account UUID is required"); + } + } + private CharacterDto toDto(Character character) { CharacterDto dto = characterMapper.toDto(character); return new CharacterDto( diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java index 1e7e410c59..89cd024d94 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java @@ -552,7 +552,10 @@ public void listCharactersByAccount( try { requireListCharactersByAccountCaller(); long tenantId = requireTenantId(request.getTenantId()); - long accountId = RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"); + java.util.UUID accountId = + java.util.UUID.fromString( + net.firedevops.firemud.common.security.JwtClaims.requireCanonicalAccountUuid( + request.getAccountId(), "accountId")); var characters = characterService .listForGameplayScope( @@ -706,7 +709,8 @@ public void createCharacter( CreateCharacterRequest request, StreamObserver responseObserver) { try { requireTenantId(request.getTenantId()); - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"); + net.firedevops.firemud.common.security.JwtClaims.requireCanonicalAccountUuid( + request.getAccountId(), "accountId"); requirePlayableStateScope(request.getPlayableStateScope()); CreateCharacterResponse response = CreateCharacterResponse.newBuilder() diff --git a/services/entity-management-service/src/main/resources/application.yml b/services/entity-management-service/src/main/resources/application.yml index 54a96253b4..dc3d49415d 100644 --- a/services/entity-management-service/src/main/resources/application.yml +++ b/services/entity-management-service/src/main/resources/application.yml @@ -76,6 +76,7 @@ firemud: public-methods: - entity_management.v1.EntityManagementService/Ping grpc: + workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} ca-cert: ${FIREMUD_GRPC_CA_CERT_PATH:certs/ca.crt} diff --git a/services/entity-management-service/src/main/resources/db/migration/V1024__ordinary_account_uuid_owner.sql b/services/entity-management-service/src/main/resources/db/migration/V1024__ordinary_account_uuid_owner.sql new file mode 100644 index 0000000000..711d6e2570 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1024__ordinary_account_uuid_owner.sql @@ -0,0 +1,7 @@ +-- Canonical Account ownership already has its own column. Retain private numeric +-- source evidence unchanged; fresh ordinary characters do not fabricate that key. +ALTER TABLE characters ALTER COLUMN account_id DROP NOT NULL; + +CREATE INDEX idx_characters_ordinary_account_uuid + ON characters (tenant_id, account_uuid, playable_state_key, id) + WHERE tenant_uuid IS NULL AND account_uuid IS NOT NULL; diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java new file mode 100644 index 0000000000..104b43cf74 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java @@ -0,0 +1,100 @@ +package net.firedevops.firemud.entitymanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; +import net.firedevops.firemud.entitymanagement.entity.Character; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +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) +@SuppressWarnings("resource") +class OrdinaryAccountUuidOwnerPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void upgradePreservesNumericSourcesAndQueriesOnlyExactOrdinaryUuidWithoutPromotion() { + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + FluentConfiguration configuration = + Flyway.configure() + .dataSource(source) + .locations("classpath:db/migration", "classpath:db/migration/saga") + .placeholders(Map.of("serviceSchema", "public")); + configuration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + configuration.target(MigrationVersion.fromVersion("1023")).load().migrate(); + var jdbc = new JdbcTemplate(source); + jdbc.update( + "INSERT INTO characters (tenant_id, account_id, name) VALUES (1, 98765, 'retained')"); + List> retained = jdbc.queryForList("SELECT * FROM characters"); + List> history = + jdbc.queryForList("SELECT * FROM flyway_schema_history ORDER BY installed_rank"); + configuration.target(MigrationVersion.fromVersion("1024")).load().migrate(); + assertThat(jdbc.queryForList("SELECT * FROM characters")).isEqualTo(retained); + var after = jdbc.queryForList("SELECT * FROM flyway_schema_history ORDER BY installed_rank"); + assertThat(after).hasSize(history.size() + 1); + assertThat(after.subList(0, history.size())).isEqualTo(history); + assertThat(after.getLast().get("version")).isEqualTo("1024"); + var repository = new CharacterRepository(DSL.using(source, SQLDialect.POSTGRES)); + UUID owner = UUID.randomUUID(); + Character ordinary = new Character(); + ordinary.setTenantId(1L); + ordinary.setAccountUuid(owner); + ordinary.setPlayableStateKey("shared-live"); + ordinary.setName("owned"); + Character saved = repository.save(ordinary); + assertThat(saved.getAccountId()).isNull(); + assertThat(saved.getAccountUuid()).isEqualTo(owner); + assertThat(saved.getActorIdentity().accountUuid()).isEqualTo(owner); + assertThat(saved.getActorIdentity().status()).isEqualTo(ActorIdentityStatus.QUARANTINED); + assertThat(saved.getActorIdentity().tenantUuid()).isNull(); + assertThat(saved.getActorIdentity().playableStateNamespaceId()).isNull(); + assertThat( + repository + .findByTenantIdAndAccountIdAndPlayableStateKey(1L, owner, "shared-live", null) + .getContent()) + .extracting(Character::getId) + .containsExactly(saved.getId()); + assertThat( + repository + .findByTenantIdAndAccountIdAndPlayableStateKey(2L, owner, "shared-live", null) + .getContent()) + .isEmpty(); + assertThat( + repository + .findByTenantIdAndAccountIdAndPlayableStateKey( + 1L, UUID.randomUUID(), "shared-live", null) + .getContent()) + .isEmpty(); + assertThat(jdbc.queryForList("SELECT * FROM characters WHERE name = 'retained'")) + .isEqualTo(retained); + assertThatThrownBy( + () -> + jdbc.update( + "UPDATE characters SET account_uuid = ? WHERE id = ?", + new UUID(0, 0), + saved.getId())) + .isInstanceOf(org.springframework.dao.DataAccessException.class); + } +} diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java index 370b925c28..cdd35ea712 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -1067,7 +1067,7 @@ private void assertNumericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAn .isEmpty(); assertThat( characterRepository.findByTenantIdAndAccountIdAndPlayableStateKey( - entityTenantRowId, 23L, namespaceUuid.toString(), Pageable.unpaged())) + entityTenantRowId, accountUuid, namespaceUuid.toString(), Pageable.unpaged())) .isEmpty(); assertThat( characterRepository.findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( @@ -1097,8 +1097,10 @@ private void assertNumericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAn .isPresent(); assertThat( characterRepository.findByTenantIdAndAccountIdAndPlayableStateKey( - entityTenantRowId, 23L, "shared-live", Pageable.unpaged())) - .hasSize(1); + entityTenantRowId, accountUuid, "shared-live", Pageable.unpaged())) + .isEmpty(); + assertThat(legacy.getAccountUuid()).isNull(); + assertThat(legacy.getAccountId()).isEqualTo(23L); assertThat( inventoryEntryRepository.findByIdCharacterIdAndCharacterTenantId( legacyCharacterId, entityTenantRowId, Pageable.unpaged())) diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index 4cd8ad5e67..7ce62e1002 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -128,10 +128,9 @@ void legacySaveAllocatesQuarantinedUuidAndPreservesLegacyReadbackAndUpdates() { assertThat( characterRepository .findByTenantIdAndAccountIdAndPlayableStateKey( - tenantId, accountId, actor.getPlayableStateKey(), null) + tenantId, accountUuid, actor.getPlayableStateKey(), null) .getContent()) - .extracting(Character::getId) - .containsExactly(actorId); + .isEmpty(); assertThat( characterRepository.findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( tenantId, actor.getPlayableStateKey(), "retained ACTOR")) @@ -643,7 +642,7 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010", "1011", "1012", "1014", "1015", "1016", "1017", "1018", "1019", "1020", "1021", - "1022", "1023"); + "1022", "1023", "1024"); assertThat(flyway.info().applied()) .filteredOn(migration -> migration.getVersion() != null) .extracting(migration -> migration.getScript()) @@ -671,9 +670,10 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { "V1020__canonical_roster_created_retirement_recognition.sql", "V1021__character_create_binary_safe_immutability.sql", "V1022__preseeded_runtime_actor_projection.sql", - "V1023__player_created_runtime_projection.sql"); + "V1023__player_created_runtime_projection.sql", + "V1024__ordinary_account_uuid_owner.sql"); assertThat(flyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1023")); + .isEqualTo(MigrationVersion.fromVersion("1024")); assertThat(flyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); @@ -747,7 +747,7 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010", "1011", "1012", "1014", "1015", "1016", "1017", "1018", "1019", "1020", "1021", - "1022", "1023"); + "1022", "1023", "1024"); assertThat(upgradedHistory) .extracting(MigrationHistoryEntry::script) .containsExactly( @@ -774,7 +774,8 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro "V1020__canonical_roster_created_retirement_recognition.sql", "V1021__character_create_binary_safe_immutability.sql", "V1022__preseeded_runtime_actor_projection.sql", - "V1023__player_created_runtime_projection.sql"); + "V1023__player_created_runtime_projection.sql", + "V1024__ordinary_account_uuid_owner.sql"); assertThat(upgradedHistory).allSatisfy(entry -> assertThat(entry.success()).isTrue()); try (Connection connection = connectToMigrationSchema(); @@ -1040,7 +1041,7 @@ private void migrateLegacySchemaToLatest() { assertThat(upgradeFlyway.getConfiguration().isOutOfOrder()).isFalse(); upgradeFlyway.migrate(); assertThat(upgradeFlyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1023")); + .isEqualTo(MigrationVersion.fromVersion("1024")); assertThat(upgradeFlyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java new file mode 100644 index 0000000000..39f6f71af7 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java @@ -0,0 +1,93 @@ +package unit.net.firedevops.firemud.entitymanagement.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.*; + +import java.lang.reflect.Field; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.entitymanagement.client.DemoAccountAuthenticationClient; +import org.junit.jupiter.api.Test; + +class DemoAccountAuthenticationClientTest { + @Test + void usesCredentialAuthenticationAndExactReturnedUuidWithoutNumericIdentity() throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + UUID actual = UUID.randomUUID(); + when(stub.authenticate(any())) + .thenReturn( + AuthenticateResponse.newBuilder() + .setAccountId(actual.toString()) + .setAuthToken("ordinary-fixture-token") + .build()); + var client = client(stub); + assertThat(client.authenticateDemoOwner()).isEqualTo(actual); + verify(stub) + .authenticate( + argThat( + request -> + request.getEmail().equals("demo@example.com") + && request.getPassword().equals("swordfish"))); + } + + @Test + void refusesUnavailableMalformedNilAndNoncanonicalOwners() throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + var client = client(stub); + for (String value : + new String[] { + "", + "1", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "11111111-1111-4111-8111-11111111111A" + }) { + when(stub.authenticate(any())) + .thenReturn( + AuthenticateResponse.newBuilder() + .setAccountId(value) + .setAuthToken("ordinary-fixture-token") + .build()); + assertThatThrownBy(client::authenticateDemoOwner) + .isInstanceOf(IllegalArgumentException.class); + } + when(stub.authenticate(any())) + .thenReturn( + AuthenticateResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("AUTH_UNAVAILABLE")) + .build()); + assertThatThrownBy(client::authenticateDemoOwner).isInstanceOf(IllegalStateException.class); + } + + private static DemoAccountAuthenticationClient client( + AccountServiceGrpc.AccountServiceBlockingStub stub) throws Exception { + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain("/fixture/client.crt"); + properties.setPrivateKey("/fixture/client.key"); + properties.setCaCert("/fixture/ca.crt"); + var client = + new DemoAccountAuthenticationClient( + new ServiceEndpointsProperties(), + properties, + mock(GrpcChannelFactory.class), + "dev", + "demo@example.com", + "swordfish"); + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + return client; + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/CharacterControllerTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/CharacterControllerTest.java index 9b8b209133..f52167aef4 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/CharacterControllerTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/CharacterControllerTest.java @@ -25,6 +25,8 @@ @WebMvcTest(CharacterController.class) class CharacterControllerTest { + private static final java.util.UUID OWNER = + java.util.UUID.fromString("11111111-1111-4111-8111-111111111111"); @Autowired private MockMvc mockMvc; @@ -32,7 +34,7 @@ class CharacterControllerTest { @BeforeEach void setUpSecurityContext() { - SessionContext.setContext("test-account", List.of("platformAdmin"), java.util.Map.of()); + SessionContext.setContext(OWNER.toString(), List.of("platformAdmin"), java.util.Map.of()); } @AfterEach @@ -46,7 +48,7 @@ void listReturnsCharacters() throws Exception { new CharacterDto( 1L, 1L, - 1L, + OWNER, "Hero", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, 1, @@ -59,7 +61,7 @@ void listReturnsCharacters() throws Exception { 5); when(characterService.listForGameplayScope( eq(1L), - eq(1L), + eq(OWNER), eq("44"), eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), any(Pageable.class))) @@ -67,7 +69,7 @@ void listReturnsCharacters() throws Exception { mockMvc .perform( - get("/tenants/1/accounts/1/characters") + get("/tenants/1/accounts/" + OWNER + "/characters") .param("gameInstanceId", "44") .param("playableStateScope", "PLAYABLE_STATE_SCOPE_SHARED")) .andExpect(status().isOk()) @@ -98,7 +100,7 @@ void listRejectsZeroAccountIdBeforeDispatch() throws Exception { .param("playableStateScope", "PLAYABLE_STATE_SCOPE_SHARED")) .andExpect(status().isBadRequest()) .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(characterService); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/data/TestDataSeederTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/data/TestDataSeederTest.java index d6bc6268c0..2362e9e86d 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/data/TestDataSeederTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/data/TestDataSeederTest.java @@ -34,13 +34,21 @@ class TestDataSeederTest { @Mock private EquipmentSlotDefinitionRepository equipmentSlotDefinitionRepository; @Mock private BodyLayoutSlotDefinitionRepository bodyLayoutSlotDefinitionRepository; + @Mock + private net.firedevops.firemud.entitymanagement.client.DemoAccountAuthenticationClient + demoAccountAuthenticationClient; + + private static final java.util.UUID OWNER = + java.util.UUID.fromString("11111111-1111-4111-8111-111111111111"); private TestDataSeeder seeder; @BeforeEach void setup() { MockitoAnnotations.openMocks(this); + when(demoAccountAuthenticationClient.authenticateDemoOwner()).thenReturn(OWNER); seeder = new TestDataSeeder( + demoAccountAuthenticationClient, characterRepository, itemRepository, itemInstanceRepository, @@ -79,6 +87,10 @@ void runSeedsCanonicalRuntimeRoomInstanceIdForRoomFixtures() throws Exception { .thenAnswer(invocation -> withContainerInstanceId(invocation.getArgument(0))); seeder.run(new DefaultApplicationArguments(new String[] {})); + ArgumentCaptor ownerCaptor = ArgumentCaptor.forClass(Character.class); + verify(characterRepository).save(ownerCaptor.capture()); + assertEquals(OWNER, ownerCaptor.getValue().getAccountUuid()); + org.junit.jupiter.api.Assertions.assertNull(ownerCaptor.getValue().getAccountId()); ArgumentCaptor itemInstanceCaptor = ArgumentCaptor.forClass(ItemInstance.class); verify(itemInstanceRepository, atLeast(1)).save(itemInstanceCaptor.capture()); @@ -99,6 +111,31 @@ void runSeedsCanonicalRuntimeRoomInstanceIdForRoomFixtures() throws Exception { assertEquals("R-1021", containerCaptor.getValue().getRoomInstanceId()); } + @Test + void refusesRetainedMissingOrMismatchedOwnershipWithoutRepair() { + for (java.util.UUID retained : new java.util.UUID[] {null, java.util.UUID.randomUUID()}) { + Character character = new Character(); + character.setId(123L); + character.setAccountId(999L); + character.setAccountUuid(retained); + when(characterRepository.findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( + 1L, "shared-live", "demo")) + .thenReturn(Optional.of(character)); + org.junit.jupiter.api.Assertions.assertThrows( + IllegalStateException.class, + () -> seeder.run(new DefaultApplicationArguments(new String[] {}))); + assertEquals(retained, character.getAccountUuid()); + assertEquals(999L, character.getAccountId()); + } + org.mockito.Mockito.verify(characterRepository, org.mockito.Mockito.never()).save(any()); + org.mockito.Mockito.verifyNoInteractions( + itemRepository, + itemInstanceRepository, + containerInstanceRepository, + equipmentSlotDefinitionRepository, + bodyLayoutSlotDefinitionRepository); + } + private Character withCharacterId(Character character) { if (character.getId() == null) { character.setId(100L); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java index 3c16b64078..9631ad6265 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java @@ -20,6 +20,9 @@ import org.springframework.data.domain.Pageable; class CharacterServiceImplListTest { + private static final java.util.UUID OWNER = + java.util.UUID.fromString("11111111-1111-4111-8111-111111111111"); + @Test void listForTenantAndAccountReturnsDtos() { CharacterRepository repo = Mockito.mock(CharacterRepository.class); @@ -39,21 +42,24 @@ void listForTenantAndAccountReturnsDtos() { Character c = new Character(); c.setId(1L); c.setTenantId(1L); - c.setAccountId(1L); + c.setAccountId(999L); + c.setAccountUuid(OWNER); c.setPlayableStateKey("shared-live"); c.setName("Hero"); when(repo.findByTenantIdAndAccountIdAndPlayableStateKey( - 1L, 1L, "shared-live", Pageable.unpaged())) + 1L, OWNER, "shared-live", Pageable.unpaged())) .thenReturn(new PageImpl<>(List.of(c))); var result = service.listForGameplayScope( - 1L, 1L, "44", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, Pageable.unpaged()); + 1L, OWNER, "44", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, Pageable.unpaged()); assertEquals(1, result.getTotalElements()); assertEquals("Hero", result.getContent().get(0).name()); + assertEquals(OWNER, result.getContent().get(0).accountId()); verify(repo) - .findByTenantIdAndAccountIdAndPlayableStateKey(1L, 1L, "shared-live", Pageable.unpaged()); + .findByTenantIdAndAccountIdAndPlayableStateKey( + 1L, OWNER, "shared-live", Pageable.unpaged()); } @Test @@ -73,14 +79,15 @@ void listForTenantAndAccountDoesNotCrossTenantBoundary() { service.initMetrics(); when(repo.findByTenantIdAndAccountIdAndPlayableStateKey( - 2L, 1L, "instance:91", Pageable.unpaged())) + 2L, OWNER, "instance:91", Pageable.unpaged())) .thenReturn(new PageImpl<>(List.of())); var result = service.listForGameplayScope( - 2L, 1L, "91", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, Pageable.unpaged()); + 2L, OWNER, "91", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, Pageable.unpaged()); assertEquals(0, result.getTotalElements()); verify(repo) - .findByTenantIdAndAccountIdAndPlayableStateKey(2L, 1L, "instance:91", Pageable.unpaged()); + .findByTenantIdAndAccountIdAndPlayableStateKey( + 2L, OWNER, "instance:91", Pageable.unpaged()); } } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java index f6b8c8bbff..c1a8bd9b14 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java @@ -40,6 +40,7 @@ void gainExperienceLevelsUp() { character.setId(1L); character.setTenantId(1L); character.setAccountId(1L); + character.setAccountUuid(java.util.UUID.fromString("11111111-1111-4111-8111-111111111111")); character.setPlayableStateKey("shared-live"); character.setName("Test"); character.setLevel(1); @@ -83,6 +84,7 @@ void getWithInventoryReturnsDto() { character.setId(1L); character.setTenantId(1L); character.setAccountId(1L); + character.setAccountUuid(java.util.UUID.fromString("11111111-1111-4111-8111-111111111111")); character.setPlayableStateKey("shared-live"); character.setName("Test"); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java index 8bf1256098..76f8604229 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java @@ -79,11 +79,12 @@ import net.firedevops.firemud.entitymanagement.v1.WearEquipmentItemResponse; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import tools.jackson.databind.ObjectMapper; class EntityManagementGrpcServiceTest { + private static final java.util.UUID ORDINARY_OWNER = + java.util.UUID.fromString("11111111-1111-4111-8111-111111111111"); private static final String TEST_NAMESPACE = "test"; private EntityManagementGrpcService configuredService( @@ -1923,26 +1924,45 @@ void listCharactersByAccountAllowsConfiguredAccountAndGameSessionWorkloadPeers() Mockito.when( characterService.listForGameplayScope( 1L, - 2L, + ORDINARY_OWNER, "44", net.firedevops.firemud.entitymanagement.v1.PlayableStateScope .PLAYABLE_STATE_SCOPE_SHARED, Pageable.unpaged())) - .thenReturn(Page.empty()); + .thenReturn( + new org.springframework.data.domain.PageImpl<>( + List.of( + new net.firedevops.firemud.entitymanagement.dto.CharacterDto( + 17L, + 1L, + ORDINARY_OWNER, + "ordinary", + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED, + 1, + 0, + 10, + 10, + 10, + 10, + 100, + 50)))); EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); - ListCharactersByAccountRequest request = characterRosterRequest("1", "2", "44"); + ListCharactersByAccountRequest request = + characterRosterRequest("1", ORDINARY_OWNER.toString(), "44"); SessionContext.clear(); for (String caller : List.of("account-service", "game-session-service")) { ListCharactersByAccountResponse response = invokeCharacterRosterWithPeer(service, request, peer(caller)); assertEquals(false, response.hasError()); + assertEquals(ORDINARY_OWNER.toString(), response.getCharacters(0).getAccountId()); } verify(characterService, org.mockito.Mockito.times(2)) .listForGameplayScope( 1L, - 2L, + ORDINARY_OWNER, "44", net.firedevops.firemud.entitymanagement.v1.PlayableStateScope .PLAYABLE_STATE_SCOPE_SHARED, @@ -1953,7 +1973,8 @@ void listCharactersByAccountAllowsConfiguredAccountAndGameSessionWorkloadPeers() void listCharactersByAccountRejectsMissingWrongAndOutOfNamespaceWorkloadPeers() { CharacterService characterService = Mockito.mock(CharacterService.class); EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); - ListCharactersByAccountRequest request = characterRosterRequest("1", "2", "44"); + ListCharactersByAccountRequest request = + characterRosterRequest("1", ORDINARY_OWNER.toString(), "44"); SessionContext.clear(); assertEquals("PERMISSION_DENIED", invokeCharacterRoster(service, request).getError().getCode()); @@ -1976,7 +1997,8 @@ service, request, peer("other-namespace", "game-session-service")) void listCharactersByAccountRequiresCertificateEvenWhenInternalJwtIsPresent() { CharacterService characterService = Mockito.mock(CharacterService.class); EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); - ListCharactersByAccountRequest request = characterRosterRequest("1", "2", "44"); + ListCharactersByAccountRequest request = + characterRosterRequest("1", ORDINARY_OWNER.toString(), "44"); SessionContext.setContext(null, List.of(), Map.of(), true, "game-session-service", "test"); try { @@ -1993,7 +2015,8 @@ void listCharactersByAccountRequiresCertificateEvenWhenInternalJwtIsPresent() { void listCharactersByAccountDeniesAuthenticatedCallerContextEvenWithWorkloadCertificate() { CharacterService characterService = Mockito.mock(CharacterService.class); EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); - ListCharactersByAccountRequest request = characterRosterRequest("1", "2", "44"); + ListCharactersByAccountRequest request = + characterRosterRequest("1", ORDINARY_OWNER.toString(), "44"); SessionContext.setContext("99", List.of(), Map.of()); try { @@ -2010,7 +2033,8 @@ void listCharactersByAccountDeniesAuthenticatedCallerContextEvenWithWorkloadCert @Test void missingOrInvalidWorkloadNamespaceDeniesCharacterRosterRead() { CharacterService characterService = Mockito.mock(CharacterService.class); - ListCharactersByAccountRequest request = characterRosterRequest("1", "2", "44"); + ListCharactersByAccountRequest request = + characterRosterRequest("1", ORDINARY_OWNER.toString(), "44"); SessionContext.clear(); for (String workloadNamespace : new String[] {null, "", " ", "not a namespace"}) { @@ -2030,11 +2054,19 @@ void listCharactersInvalidAccountIdReturnsErrorDetail() { EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); SessionContext.clear(); - ListCharactersByAccountResponse response = - invokeCharacterRosterWithPeer( - service, characterRosterRequest("1", "bad", "44"), peer("game-session-service")); - - assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + for (String invalid : + List.of( + "bad", + "1", + "00000000-0000-0000-0000-000000000000", + "11111111-1111-4111-8111-11111111111A", + " " + ORDINARY_OWNER)) { + ListCharactersByAccountResponse response = + invokeCharacterRosterWithPeer( + service, characterRosterRequest("1", invalid, "44"), peer("game-session-service")); + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + } + verifyNoInteractions(characterService); } @Test @@ -2152,7 +2184,7 @@ public void onCompleted() {} }); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertEquals("Malformed claim: accountId", ref.get().getError().getMessage()); verifyNoInteractions(characterService); } @@ -2179,7 +2211,7 @@ void createCharacterDeniesValidSharedAndIsolatedRequestsBeforeAllocation() { service.createCharacter( net.firedevops.firemud.entitymanagement.v1.CreateCharacterRequest.newBuilder() .setTenantId("1") - .setAccountId("44") + .setAccountId(ORDINARY_OWNER.toString()) .setGameInstanceId("44") .setPlayableStateScope(scope) .setName("Ember") @@ -2231,7 +2263,7 @@ void listCharactersUnexpectedErrorReturnsInternal() { Mockito.when( characterService.listForGameplayScope( 1L, - 1L, + ORDINARY_OWNER, "44", net.firedevops.firemud.entitymanagement.v1.PlayableStateScope .PLAYABLE_STATE_SCOPE_SHARED, @@ -2242,7 +2274,9 @@ void listCharactersUnexpectedErrorReturnsInternal() { ListCharactersByAccountResponse response = invokeCharacterRosterWithPeer( - service, characterRosterRequest("1", "1", "44"), peer("game-session-service")); + service, + characterRosterRequest("1", ORDINARY_OWNER.toString(), "44"), + peer("game-session-service")); assertNotNull(response); assertEquals("INTERNAL", response.getError().getCode()); From be9c4abb3027de006232f5e02766e666f1c3bcfa Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 08:29:14 +1300 Subject: [PATCH 16/34] Permit ordinary UUID owners without promoting canonical actor provenance --- .../gameplay-rules-entities-and-effects.md | 2 +- .../V1024__ordinary_account_uuid_owner.sql | 32 ++++++ ...countUuidOwnerPostgresIntegrationTest.java | 98 +++++++++++++++++-- ...eseededActorAssignmentIntegrationTest.java | 5 +- ...haracterCreatePostgresIntegrationTest.java | 6 +- ...ntakeMigrationPostgresIntegrationTest.java | 2 +- .../DemoAccountAuthenticationClientTest.java | 4 + 7 files changed, 132 insertions(+), 17 deletions(-) diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index af5a6de3dc..85e410c279 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -251,7 +251,7 @@ The next review correction at code checkpoint `ce02d51f608f199e531de32c1d15f63cb The local ordinary receiving boundary uses the existing persisted Account UUID for character DTOs, strict wire readers, roster/name projections, service inputs and nested character copies. Numeric Account source-row evidence remains retained and is excluded from public identity. Forward V1024 changes nullability/indexing without mapping or rewriting retained ownership. Explicit demo seeding obtains the owner from real Account credential authentication and refuses missing/mismatched retained ownership. The [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#ordinary-account-ownership) owns the contract. -Focused authored proof covers canonical UUID projection and tenant/owner isolation, preserved numeric-source rows, migration history, nil rejection, missing/mismatched seed-owner refusal and actual authentication-response validation with controlled collaborators. The authorized Entity formatting/main/unit/native compilation selection passes after two old numeric roster fixture calls were corrected; its first failed native compilation and successful recovery remain separately retained. These are compilation results, not test execution. Unit/native execution, actual mTLS seed authentication and fresh-image LOGIN/PLAY/LOOK remain pending Root's consolidated qualification. Existing canonical actor/created-origin provenance, unregistered owner machinery, production custody, admission and activation holds remain unchanged. +Full Entity proof executes 462 unit and 135 native PostgreSQL cases without failures, errors or skips, including canonical UUID projection, exact tenant/owner isolation, retained numeric-source rows/xmin and migration history, nil/partial-canonical/promotion refusal, unchanged created-actor guards, and missing/mismatched seed-owner refusal. Authentication-response validation uses controlled collaborators. Generation, enabled analysis, formatting and documentation pass; failed initial aggregates and recovery attribution remain in the review records. Separate final Game Session qualification passes 41 native HTTP/login/WebSocket/retirement cases. Actual mTLS seed authentication and fresh-image LOGIN/PLAY/LOOK remain pending. Existing canonical actor/created-origin provenance, unregistered owner machinery, production custody, admission and activation holds remain unchanged. ## Active Gaps diff --git a/services/entity-management-service/src/main/resources/db/migration/V1024__ordinary_account_uuid_owner.sql b/services/entity-management-service/src/main/resources/db/migration/V1024__ordinary_account_uuid_owner.sql index 711d6e2570..597ed68634 100644 --- a/services/entity-management-service/src/main/resources/db/migration/V1024__ordinary_account_uuid_owner.sql +++ b/services/entity-management-service/src/main/resources/db/migration/V1024__ordinary_account_uuid_owner.sql @@ -5,3 +5,35 @@ ALTER TABLE characters ALTER COLUMN account_id DROP NOT NULL; CREATE INDEX idx_characters_ordinary_account_uuid ON characters (tenant_id, account_uuid, playable_state_key, id) WHERE tenant_uuid IS NULL AND account_uuid IS NOT NULL; + +-- Preserve every existing core/provenance requirement. Ordinary UUID ownership +-- alone carries no canonical tenant, namespace, scope, or actor-promotion evidence. +/* [jooq ignore start] */ +ALTER TABLE characters DROP CONSTRAINT ck_character_created_core; + +ALTER TABLE characters ADD CONSTRAINT ck_character_created_core CHECK ( + (actor_entry_policy IS NULL AND creation_target_namespace IS NULL + AND creation_operation_id IS NULL AND authored_initial_core_json IS NULL + AND creation_descriptor_json IS NULL AND creation_descriptor_digest IS NULL + AND (account_id IS NOT NULL OR ( + account_uuid IS NOT NULL + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_uuid IS NULL AND playable_state_namespace_id IS NULL + AND playable_state_scope IS NULL AND actor_identity_status = 'QUARANTINED' + )) AND playable_state_key IS NOT NULL + AND level IS NOT NULL AND experience IS NOT NULL AND strength IS NOT NULL + AND agility IS NOT NULL AND intelligence IS NOT NULL AND stamina IS NOT NULL + AND health IS NOT NULL AND mana IS NOT NULL AND body_layout_key IS NOT NULL) + OR (actor_entry_policy = 'PLAYER_CREATED' AND creation_target_namespace IS NOT NULL + AND creation_operation_id IS NOT NULL + AND actor_identity_status IN ('OWNER_RESOLVED', 'QUARANTINED') + AND account_id IS NULL AND playable_state_key IS NULL + AND level IS NULL AND experience IS NULL AND strength IS NULL AND agility IS NULL + AND intelligence IS NULL AND stamina IS NULL AND health IS NULL AND mana IS NULL + AND body_layout_key IS NULL AND authored_initial_core_json IS NOT NULL + AND creation_descriptor_json IS NOT NULL + AND creation_descriptor_digest IS NOT NULL + AND creation_descriptor_digest ~ '^sha256:[0-9a-f]{64}$' + AND name = authored_initial_core_json::JSONB ->> 'displayName') +); +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java index 104b43cf74..4732611901 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java @@ -47,11 +47,28 @@ void upgradePreservesNumericSourcesAndQueriesOnlyExactOrdinaryUuidWithoutPromoti var jdbc = new JdbcTemplate(source); jdbc.update( "INSERT INTO characters (tenant_id, account_id, name) VALUES (1, 98765, 'retained')"); - List> retained = jdbc.queryForList("SELECT * FROM characters"); + List> retained = + jdbc.queryForList("SELECT *, xmin::text AS retained_xmin FROM characters"); List> history = jdbc.queryForList("SELECT * FROM flyway_schema_history ORDER BY installed_rank"); + String parentCore = + java.util.Objects.requireNonNull( + jdbc.queryForObject( + "SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conrelid = 'characters'::regclass AND conname = 'ck_character_created_core'", + String.class)); configuration.target(MigrationVersion.fromVersion("1024")).load().migrate(); - assertThat(jdbc.queryForList("SELECT * FROM characters")).isEqualTo(retained); + String currentCore = + java.util.Objects.requireNonNull( + jdbc.queryForObject( + "SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conrelid = 'characters'::regclass AND conname = 'ck_character_created_core'", + String.class)); + assertThat(parentCore).contains("'PLAYER_CREATED'"); + assertThat(currentCore).contains("'PLAYER_CREATED'"); + assertThat(currentCore.substring(currentCore.indexOf("'PLAYER_CREATED'"))) + .isEqualTo(parentCore.substring(parentCore.indexOf("'PLAYER_CREATED'"))); + + assertThat(jdbc.queryForList("SELECT *, xmin::text AS retained_xmin FROM characters")) + .isEqualTo(retained); var after = jdbc.queryForList("SELECT * FROM flyway_schema_history ORDER BY installed_rank"); assertThat(after).hasSize(history.size() + 1); assertThat(after.subList(0, history.size())).isEqualTo(history); @@ -64,6 +81,9 @@ void upgradePreservesNumericSourcesAndQueriesOnlyExactOrdinaryUuidWithoutPromoti ordinary.setPlayableStateKey("shared-live"); ordinary.setName("owned"); Character saved = repository.save(ordinary); + Character loaded = repository.findById(saved.getId()).orElseThrow(); + assertThat(loaded.getAccountUuid()).isEqualTo(owner); + assertThat(loaded.getAccountId()).isNull(); assertThat(saved.getAccountId()).isNull(); assertThat(saved.getAccountUuid()).isEqualTo(owner); assertThat(saved.getActorIdentity().accountUuid()).isEqualTo(owner); @@ -87,14 +107,72 @@ void upgradePreservesNumericSourcesAndQueriesOnlyExactOrdinaryUuidWithoutPromoti 1L, UUID.randomUUID(), "shared-live", null) .getContent()) .isEmpty(); - assertThat(jdbc.queryForList("SELECT * FROM characters WHERE name = 'retained'")) + assertThat( + jdbc.queryForList( + "SELECT *, xmin::text AS retained_xmin FROM characters WHERE name = 'retained'")) + .isEqualTo(retained); + List> ordinaryBeforeRefusals = + jdbc.queryForList( + "SELECT *, xmin::text AS retained_xmin FROM characters WHERE id = ?", saved.getId()); + for (String invalidChange : + List.of( + "account_uuid = NULL", + "account_uuid = '00000000-0000-0000-0000-000000000000'::UUID", + "tenant_uuid = '11111111-1111-4111-8111-111111111111'::UUID", + "playable_state_namespace_id = '22222222-2222-4222-8222-222222222222'::UUID", + "playable_state_scope = 'PLAYABLE_STATE_SCOPE_SHARED'", + "actor_identity_status = 'OWNER_RESOLVED', actor_identity_quarantine_reason = NULL", + "actor_identity_status = 'OWNER_RESOLVED', actor_identity_quarantine_reason = NULL, " + + "tenant_uuid = '11111111-1111-4111-8111-111111111111'::UUID, " + + "playable_state_namespace_id = '22222222-2222-4222-8222-222222222222'::UUID, " + + "playable_state_scope = 'PLAYABLE_STATE_SCOPE_SHARED'", + "actor_identity_quarantine_reason = NULL", + "actor_entry_policy = 'PLAYER_CREATED'", + "creation_target_namespace = 'dev'", + "creation_operation_id = '33333333-3333-4333-8333-333333333333'::UUID", + "authored_initial_core_json = '{}'", + "creation_descriptor_json = '{}'", + "creation_descriptor_digest = 'sha256:" + "a".repeat(64) + "'")) { + assertThatThrownBy( + () -> + jdbc.update( + "UPDATE characters SET " + invalidChange + " WHERE id = ?", saved.getId())) + .as(invalidChange) + .isInstanceOf(org.springframework.dao.DataAccessException.class); + assertThat( + jdbc.queryForList( + "SELECT *, xmin::text AS retained_xmin FROM characters WHERE id = ?", + saved.getId())) + .isEqualTo(ordinaryBeforeRefusals); + } + for (String requiredColumn : + List.of( + "playable_state_key", + "level", + "experience", + "strength", + "agility", + "intelligence", + "stamina", + "health", + "mana", + "body_layout_key")) { + assertThatThrownBy( + () -> + jdbc.update( + "UPDATE characters SET " + requiredColumn + " = NULL WHERE id = ?", + saved.getId())) + .as(requiredColumn) + .isInstanceOf(org.springframework.dao.DataAccessException.class); + } + assertThat( + jdbc.queryForList( + "SELECT *, xmin::text AS retained_xmin FROM characters WHERE id = ?", + saved.getId())) + .isEqualTo(ordinaryBeforeRefusals); + assertThat( + jdbc.queryForList( + "SELECT *, xmin::text AS retained_xmin FROM characters WHERE name = 'retained'")) .isEqualTo(retained); - assertThatThrownBy( - () -> - jdbc.update( - "UPDATE characters SET account_uuid = ? WHERE id = ?", - new UUID(0, 0), - saved.getId())) - .isInstanceOf(org.springframework.dao.DataAccessException.class); } } diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java index cdd35ea712..b2d977b915 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -505,7 +505,7 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( .extracting(AppliedMigration::version) .containsExactly( "1006", "1007", "1008", "1009", "1010", "1011", "1012", "1014", "1015", "1016", "1017", - "1018", "1019", "1020", "1021", "1022", "1023"); + "1018", "1019", "1020", "1021", "1022", "1023", "1024"); assertThat(successorHistory) .extracting(AppliedMigration::script) .containsExactly( @@ -525,7 +525,8 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( "V1020__canonical_roster_created_retirement_recognition.sql", "V1021__character_create_binary_safe_immutability.sql", "V1022__preseeded_runtime_actor_projection.sql", - "V1023__player_created_runtime_projection.sql"); + "V1023__player_created_runtime_projection.sql", + "V1024__ordinary_account_uuid_owner.sql"); assertThat(successorHistory).extracting(AppliedMigration::checksum).doesNotContainNull(); try (Connection connection = connectToSchema(schema)) { diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java index 800d479fb4..14d22663a2 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java @@ -137,7 +137,7 @@ void upgradesActualEntity1014ParentWithoutChangingRetainedActorOrRosterRows() { DSLContext upgradedDsl = DSL.using(parentDataSource, SQLDialect.POSTGRES); assertThat(migrationHistory(upgradedDsl).subList(0, parentHistory.size())) .containsExactlyElementsOf(parentHistory); - assertThat(migrationVersions(upgradedDsl)).contains("1017").last().isEqualTo("1023"); + assertThat(migrationVersions(upgradedDsl)).contains("1017").last().isEqualTo("1024"); assertThat(retainedParentRows(upgradedDsl, character, snapshot)) .containsExactlyElementsOf(retainedRows); assertThat( @@ -183,7 +183,7 @@ void binaryGuardUpgradePreservesCreatedRowsHistoryAndTerminalReplay() throws Exc assertThat(migrationHistory(retainedDsl).subList(0, historyBefore.size())) .containsExactlyElementsOf(historyBefore); - assertThat(migrationVersions(retainedDsl)).last().isEqualTo("1023"); + assertThat(migrationVersions(retainedDsl)).last().isEqualTo("1024"); assertThat(retainedDsl.fetch(retainedRowsSql).getValues(0, String.class)) .containsExactlyElementsOf(before); assertThat(retainedRepository.settle(retainedProof, null)).isEqualTo(terminal); @@ -256,7 +256,7 @@ void upgradesRetainedV1016CreatedActorBeforeQuarantineWithoutChangingRows() thro migrate(retainedDataSource, retainedSchema, null); - assertThat(migrationVersions(retainedDsl)).contains("1017").last().isEqualTo("1023"); + assertThat(migrationVersions(retainedDsl)).contains("1017").last().isEqualTo("1024"); assertThat(retainedRow(retainedDsl, "characters", "character_uuid", characterId)) .isEqualTo(actorBefore); assertThat( diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java index 9d6c801910..2694d5ea72 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java @@ -106,7 +106,7 @@ void seedLegacyRowsBeforeV1011() { dsl.fetchSingle( "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") .get(0, String.class)) - .isEqualTo("1023"); + .isEqualTo("1024"); } @AfterEach diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java index 39f6f71af7..bfaa567571 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java @@ -88,6 +88,10 @@ private static DemoAccountAuthenticationClient client( Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); field.setAccessible(true); field.set(client, stub); + Field initialized = + AbstractReloadingBlockingGrpcClient.class.getDeclaredField("explicitlyInitialized"); + initialized.setAccessible(true); + initialized.setBoolean(client, true); return client; } } From 81fcde7c4049b0be4aa67c1b09f5d4c68db667f2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 09:06:13 +1300 Subject: [PATCH 17/34] Prove real mTLS Entity UUID owner and tenant isolation --- .../gameplay-rules-entities-and-effects.md | 2 +- ...countUuidOwnerPostgresIntegrationTest.java | 179 +++++++++++++++++- 2 files changed, 179 insertions(+), 2 deletions(-) diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 85e410c279..b3a4b263b7 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -251,7 +251,7 @@ The next review correction at code checkpoint `ce02d51f608f199e531de32c1d15f63cb The local ordinary receiving boundary uses the existing persisted Account UUID for character DTOs, strict wire readers, roster/name projections, service inputs and nested character copies. Numeric Account source-row evidence remains retained and is excluded from public identity. Forward V1024 changes nullability/indexing without mapping or rewriting retained ownership. Explicit demo seeding obtains the owner from real Account credential authentication and refuses missing/mismatched retained ownership. The [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#ordinary-account-ownership) owns the contract. -Full Entity proof executes 462 unit and 135 native PostgreSQL cases without failures, errors or skips, including canonical UUID projection, exact tenant/owner isolation, retained numeric-source rows/xmin and migration history, nil/partial-canonical/promotion refusal, unchanged created-actor guards, and missing/mismatched seed-owner refusal. Authentication-response validation uses controlled collaborators. Generation, enabled analysis, formatting and documentation pass; failed initial aggregates and recovery attribution remain in the review records. Separate final Game Session qualification passes 41 native HTTP/login/WebSocket/retirement cases. Actual mTLS seed authentication and fresh-image LOGIN/PLAY/LOOK remain pending. Existing canonical actor/created-origin provenance, unregistered owner machinery, production custody, admission and activation holds remain unchanged. +Full Entity proof executes 462 unit and 135 native PostgreSQL cases without failures, errors or skips, including canonical UUID projection, exact tenant/owner isolation, retained numeric-source rows/xmin and migration history, nil/partial-canonical/promotion refusal, unchanged created-actor guards, and missing/mismatched seed-owner refusal. Authentication-response validation uses controlled collaborators. Generation, enabled analysis, formatting and documentation pass; failed initial aggregates and recovery attribution remain in the review records. Separate final Game Session qualification passes 41 native HTTP/login/WebSocket/retirement cases. Fresh packaged images pass held public-edge denial and the separate real-backend mTLS LOGIN/PLAY/LOOK baseline using actual Account-authenticated Entity seeding. Authenticated cleanup and independent exact-project checks confirm no remaining containers, networks or volumes. Additional certificate-derived mTLS receiver-to-PostgreSQL proof passes exact-owner success, wrong-owner/tenant no-disclosure, unresolved numeric-owner refusal, wrong-service/namespace denial and unchanged rows/xmin. Its controlled PKI and SQL fixtures complement the genuine Account seed and packaged runtime; they do not independently qualify production PKI, Spring registration or Account issuance. Existing canonical actor/created-origin provenance, unregistered owner machinery, production custody, admission and activation holds remain unchanged. ## Active Gaps diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java index 4732611901..62ecac78b6 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java @@ -3,12 +3,34 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.nio.file.Path; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; import net.firedevops.firemud.entitymanagement.entity.Character; +import net.firedevops.firemud.entitymanagement.mapper.CharacterMapper; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.PlayableStateKeyResolver; +import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; +import net.firedevops.firemud.entitymanagement.service.impl.CharacterServiceImpl; +import net.firedevops.firemud.entitymanagement.service.impl.EntityManagementGrpcService; +import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; @@ -17,6 +39,10 @@ import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mapstruct.factory.Mappers; +import org.mockito.Mockito; +import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.containers.PostgreSQLContainer; @@ -26,12 +52,15 @@ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class OrdinaryAccountUuidOwnerPostgresIntegrationTest { + @TempDir Path tlsDirectory; + @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test - void upgradePreservesNumericSourcesAndQueriesOnlyExactOrdinaryUuidWithoutPromotion() { + void upgradePreservesNumericSourcesAndQueriesOnlyExactOrdinaryUuidWithoutPromotion() + throws Exception { var source = new DriverManagerDataSource( postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); @@ -111,6 +140,7 @@ void upgradePreservesNumericSourcesAndQueriesOnlyExactOrdinaryUuidWithoutPromoti jdbc.queryForList( "SELECT *, xmin::text AS retained_xmin FROM characters WHERE name = 'retained'")) .isEqualTo(retained); + assertMtlsReceiverOwnerAndTenantIsolation(repository, jdbc, saved, owner); List> ordinaryBeforeRefusals = jdbc.queryForList( "SELECT *, xmin::text AS retained_xmin FROM characters WHERE id = ?", saved.getId()); @@ -175,4 +205,151 @@ void upgradePreservesNumericSourcesAndQueriesOnlyExactOrdinaryUuidWithoutPromoti "SELECT *, xmin::text AS retained_xmin FROM characters WHERE name = 'retained'")) .isEqualTo(retained); } + + /** + * Real TLS/receiver/service/mapper/PostgreSQL composition, using controlled PKI and owner rows. + * R1274 separately proves Account-authenticated seeding and packaged Spring runtime wiring; this + * harness does not establish production PKI, Account issuance or public admission. + */ + private void assertMtlsReceiverOwnerAndTenantIsolation( + CharacterRepository repository, JdbcTemplate jdbc, Character saved, UUID owner) + throws Exception { + String namespace = "ordinary-owner-proof"; + var pki = + LoopbackMtlsTestPki.create( + tlsDirectory, + "Ordinary Entity owner proof CA", + new LoopbackMtlsTestPki.IdentitySpec( + "entity", + "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service", + true), + new LoopbackMtlsTestPki.IdentitySpec( + "gs", "spiffe://firemud/ns/" + namespace + "/sa/game-session-service", false), + new LoopbackMtlsTestPki.IdentitySpec( + "foreign", "spiffe://firemud/ns/other/sa/game-session-service", false), + new LoopbackMtlsTestPki.IdentitySpec( + "social", "spiffe://firemud/ns/" + namespace + "/sa/social-groups-service", false)); + var meters = new SimpleMeterRegistry(); + var stateKeys = new PlayableStateKeyResolver(); + var characters = + new CharacterServiceImpl( + repository, + Mappers.getMapper(CharacterMapper.class), + new ConcurrentMapCacheManager("characterGraph"), + meters, + stateKeys, + new ScopedCharacterResolver(repository, stateKeys)); + var receiver = + new EntityManagementGrpcService( + Mockito.mock(net.firedevops.firemud.entitymanagement.service.PingService.class), + characters, + Mockito.mock(net.firedevops.firemud.entitymanagement.service.ActorStateService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.ActorConditionMutationService + .class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService + .class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.EquipmentService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.InventoryService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.ContainerService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.RoomEntityService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService + .class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.impl + .EntityMutationEffectReplayService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.EntityUpgradeValidationService + .class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.EntityTemplateReferenceService + .class), + Mockito.mock( + net.firedevops.firemud.common.security.GameplaySessionAttestationService.class), + meters, + Mockito.mock(net.firedevops.firemud.entitymanagement.effect.EffectPayloadParser.class), + namespace); + List> before = + jdbc.queryForList("SELECT *, xmin::text AS retained_xmin FROM characters ORDER BY id"); + var identity = pki.identity("entity"); + Server server = + NettyServerBuilder.forPort(0) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(receiver, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + try { + for (String alias : List.of("gs", "foreign", "social")) { + var caller = pki.identity(alias); + ManagedChannel channel = + NettyChannelBuilder.forAddress("localhost", server.getPort()) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(pki.caCertificate()) + .keyManager(caller.privateKey(), caller.certificate(), pki.caCertificate()) + .build()) + .intercept( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service")) + .build(); + try { + var stub = + EntityManagementServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS); + var exact = stub.listCharactersByAccount(rosterRequest("1", owner.toString())); + if (!alias.equals("gs")) { + assertThat(exact.hasError()).isTrue(); + assertThat(exact.getError().getCode()).isEqualTo("PERMISSION_DENIED"); + assertThat(exact.getCharactersList()).isEmpty(); + continue; + } + assertThat(exact.hasError()).isFalse(); + assertThat(exact.getCharactersCount()).isEqualTo(1); + assertThat(exact.getCharacters(0).getId()).isEqualTo(saved.getId().toString()); + assertThat(exact.getCharacters(0).getAccountId()).isEqualTo(owner.toString()); + assertThat(exact.getCharacters(0).getTenantId()).isEqualTo("1"); + for (var request : + List.of( + rosterRequest("1", UUID.randomUUID().toString()), + rosterRequest("2", owner.toString()))) { + var denied = stub.listCharactersByAccount(request); + assertThat(denied.hasError()).isFalse(); + assertThat(denied.getCharactersList()).isEmpty(); + } + // Retained numeric source evidence is not a public Account selector. + var unresolved = stub.listCharactersByAccount(rosterRequest("1", "98765")); + assertThat(unresolved.hasError()).isTrue(); + assertThat(unresolved.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(unresolved.getCharactersList()).isEmpty(); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + assertThat( + jdbc.queryForList( + "SELECT *, xmin::text AS retained_xmin FROM characters ORDER BY id")) + .isEqualTo(before); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + meters.close(); + } + } + + private static ListCharactersByAccountRequest rosterRequest(String tenant, String owner) { + return ListCharactersByAccountRequest.newBuilder() + .setTenantId(tenant) + .setAccountId(owner) + .setGameInstanceId("44") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build(); + } } From c53106ca8e93a9487a643e95da737ef714f018a8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 09:44:56 +1300 Subject: [PATCH 18/34] docs: align final UUID receiving contracts and proof status --- .../account-service/api-contracts.md | 6 +++--- .../account-service/runtime-and-data.md | 12 ++++++------ .../player-access-and-session.md | 18 +++++++++--------- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index dd589ef066..edf6285168 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -90,7 +90,7 @@ Account has unregistered individual Creator Party, hosted-terms catalog, and ind `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. -The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` and `ExportAccount` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. PostgreSQL runtime proof for retry/recovery after an unknown commit outcome and direct text end-to-end proof remain open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` after bootstrap and scope validation, before replay or admission-authority reads, token minting, or replay/session mutation; cached-success replay and current membership, entitlement, grant, and pointer checks do not execute on this path. For text `PLAY`, the consumer currently proceeds only when `membershipExists` and `gameplayAdmissionAllowed` are true; it does not enforce the emitted `membershipLifecycleState` or `membershipAuthorityGeneration`. For eligible public-production text `PLAY`, missing or existing non-admitting membership may currently produce `JOIN_REQUIRED`. This text consumer therefore does not distinguish `INACTIVE` from another existing non-admitting state even though Account emits the lifecycle field. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The unpublished receiving source also carries UUID ordinary login results and credentials; tenant identifiers remain numeric, while complete registry/profile and membership-authority qualification remains held. Derived `bootstrap-connect-scope` artifacts also use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Incoming direct-text `PlayerExecutionContext.account_id` and the Account-to-Entity character-discovery Account reference remain separate unconverted numeric wire boundaries. The bounded response and REST selector identity contract is defined below; migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. +The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` and `ExportAccount` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. PostgreSQL runtime proof for retry/recovery after an unknown commit outcome and direct text end-to-end proof remain open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` after bootstrap and scope validation, before replay or admission-authority reads, token minting, or replay/session mutation; cached-success replay and current membership, entitlement, grant, and pointer checks do not execute on this path. For text `PLAY`, the consumer currently proceeds only when `membershipExists` and `gameplayAdmissionAllowed` are true; it does not enforce the emitted `membershipLifecycleState` or `membershipAuthorityGeneration`. For eligible public-production text `PLAY`, missing or existing non-admitting membership may currently produce `JOIN_REQUIRED`. This text consumer therefore does not distinguish `INACTIVE` from another existing non-admitting state even though Account emits the lifecycle field. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers; tenant identifiers remain numeric. Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. ### Account UUID Response and REST Selector Identity @@ -98,7 +98,7 @@ The account lifecycle API, export surfaces, and deletion-precondition contracts The implemented legacy profile REST handlers and five global Account REST handlers listed under [REST APIs](#rest-apis) accept only canonical lowercase non-nil Account UUID selectors. Account resolves them through `resolveAccountStorageId(UUID)`, including persisted provenance and source-row validation, before passing private numeric keys to existing Account-local services. Malformed, numeric, nil, uppercase or otherwise noncanonical selectors, and profile PUT path/body mismatches, are invalid arguments; inconsistent or unavailable owner evidence returns `AUTH_UNAVAILABLE`. A well-formed selector with no Account owner returns the same `403 PERMISSION_DENIED` and generic `Account access required` message as an existing owner the caller cannot access. Endpoint-specific authorization and status consequences remain below. -The unpublished receiving composition also carries UUID ordinary JWT subjects/Account claims, UUID shared forwarding and UUID internal Account selectors, keeping numeric SQL rows private to Account. Tenant identifiers remain numeric; complete token-profile/registry and canonical route authorization remain unqualified. It does not qualify canonical tenant-scoped profile routes, complete portable or tenant-wide exports, token registry behavior, production credential custody, public JOIN exposure or gameplay activation. Implementation and focused proof limits belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-owned-response-uuid-projection). +The final ordinary receiving composition carries UUID ordinary JWT subjects/Account claims, UUID shared forwarding and UUID internal Account selectors, keeping numeric SQL rows private to Account. Profile `SessionContext` self-binding and global REST caller proof use that same UUID identity. Tenant identifiers remain numeric. Full token-profile/registry qualification, canonical tenant-scoped profile routes, complete portable or tenant-wide exports, production credential custody, public JOIN exposure and gameplay activation remain unqualified. Implementation and focused proof limits belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). ### Current vs Target Export Lifecycle @@ -307,7 +307,7 @@ Implemented Account-valued REST selectors and response fields use canonical Acco | `GET` | `/support/tenants/{tenantId}/entitlements` | Cross-tenant support-safe entitlement view with redacted fields | | `GET` | `/.well-known/jwks.json` | JWKS for verifying issued JWTs | -The listed Account UUID representation does not imply full receiver convergence. Numeric legacy fields and privileged internal Account surfaces remain separate gaps; see the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-account-uuid-receiving-preparation). +The listed Account UUID representation is implemented through the qualified ordinary receiving boundary, including Account-issued credentials, shared forwarding, caller-bound REST/profile use, and UUID-valued downstream Account references. Private numeric Account rows and the separate legacy numeric GameInstance owner/StartSession boundary remain distinct. Full token-profile/registry qualification, production custody and gameplay admission/activation remain held; proof status is in the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). Current verification routing/auth status: `POST /auth/verify-email` inherits bearer authentication because both HTTP configurations allowlist only `GET /auth/verify-email`, while that allowlisted GET has no controller mapping; see the existing [verification-routing gap in Runtime and Data](./runtime-and-data.md#email-and-notification-design). diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 12a7531e60..8784b27dc9 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,15 +8,15 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status -Both existing `bootstrap-connect-scope` producer paths mint the exact persisted Account UUID. Scope validation compares canonical UUID subject/Account claims before owner readback; malformed identity remains `CONNECT_SCOPE_INVALID`, while unavailable owner evidence is `AUTH_UNAVAILABLE`. Retained scope/JOIN rows and digests continue to use private Account row keys without a schema rewrite. This does not convert the incoming direct-text caller Account wire or Account-to-Entity wire, and adds no Game Session text dispatch. Proof and retained-scope rediscovery limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#bootstrap-connect-scope-uuid-artifact). +Both existing `bootstrap-connect-scope` producer paths mint the exact persisted Account UUID. Scope validation compares canonical UUID subject/Account claims before owner readback; malformed identity remains `CONNECT_SCOPE_INVALID`, while unavailable owner evidence is `AUTH_UNAVAILABLE`. Retained scope/JOIN rows and digests continue to use private Account row keys without a schema rewrite. This scope-artifact transition itself adds no Game Session text dispatch; the separately qualified ordinary receiving cohort now carries UUID Account identity through the direct-text caller context and Account-to-Entity references. Proof and retained-scope rediscovery limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#bootstrap-connect-scope-uuid-artifact) and [ordinary UUID receiving](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). JOIN keeps numeric owner keys inside its retained scope, operation, membership and digest records. A private in-process outcome is projected through full Account owner readback only after the JOIN transaction returns, so response identity failure cannot undo a committed receipt or replace its original outcome. Profile repositories embed only partial Account rows; GET/UPDATE response projection rereads the full owner and supplies its verified UUID to the generated mapper. Both existing export paths verify their already-loaded Account once and reuse that UUID while retaining each profile owner, tenant and mapped-output check. The response identity contract is owned by [Account API contracts](./api-contracts.md); implementation and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-owned-response-uuid-projection). -The `player-bootstrap` credential/result profile uses the persisted Account UUID. Its dedicated reader requires canonical non-nil UUID subject/Account-claim equality and existing Account-owner readback before accessing Account-local session state. Numeric storage keys remain private at this lookup. The separate derived-scope UUID artifact transition is recorded above; JOIN-result and Account-to-Entity wire identities, full registry qualification and gameplay activation remain outside the credential profile. Current proof limits belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#player-bootstrap-uuid-credential-profile). +The `player-bootstrap` credential/result profile uses the persisted Account UUID. Its dedicated reader requires canonical non-nil UUID subject/Account-claim equality and Account-owner readback before accessing Account-local session state. Numeric storage keys remain private at this lookup. The derived-scope artifact and JOIN result also use Account UUIDs; the final ordinary receiving cohort carries UUID Account identity through shared context, internal Account selectors and downstream consumer references. Full token-profile/registry qualification, production credential custody and gameplay activation remain held. Current proof limits belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). -Ordinary control-UI, gameplay password/email-OTP, and player-bootstrap issuance now checks the authenticated Account's persisted UUID provenance and source-row identity and resolves that UUID back to the same Account row before consuming a successful challenge, signing, or storing a session. Identity readback failures use `AUTH_UNAVAILABLE`; invalid credentials retain their existing response. The published Account-local owner preparation left ordinary control-UI/gameplay authentication numeric; the separate local receiving composition now issues UUID identity while full profile/registry qualification remains held. Its focused proof and remaining coordinated UUID activation scope are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-account-authentication-owner-preparation). +Ordinary control-UI, gameplay password/email-OTP, and player-bootstrap issuance checks the authenticated Account's persisted UUID provenance and source-row identity and resolves that UUID back to the same Account row before consuming a successful challenge, signing, or storing a session. Successful ordinary authentication results and Account-issued JWT subject/Account claims carry that UUID. Identity readback failures use `AUTH_UNAVAILABLE`; invalid credentials retain their existing response. The final ordinary receiving qualification and its limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). -The global Account REST selectors resolve the public UUID to the existing private numeric row before Account-local service calls; this future composition retains exact UUID `SessionContext` self/role authorization and the existing numeric tenant storage selectors. B’s published REST-only boundary used legacy numeric caller binding; its proof remains separately attributed. The [Account API contract](./api-contracts.md#rest-apis) owns accepted selector and failure behavior; gRPC/Logging callers, token profiles and production authorization custody remain separate. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-owned-global-rest-uuid-selectors) records implementation and focused proof. +The global Account REST selectors resolve public UUIDs to private numeric rows before Account-local service calls. The final composition uses exact UUID `SessionContext` self/role authorization for global selectors and profile callers; tenant storage selectors retain their current numeric representation. The earlier published REST-only boundary used legacy numeric caller binding and remains historical proof for that source. The [Account API contract](./api-contracts.md#rest-apis) owns accepted selector and failure behavior; full token-profile qualification and production authorization custody remain separate. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving) records current implementation and focused proof. The caller verifier, lease owner and certificate-guarded seven-method receiver remain manually composed and unregistered. Their [lease contract](./api-contracts.md#canonical-public-production-new-admission-lease-source) preserves immutable original attempts and ACKs, with full tenant-source guards for new acquisition and first finalization and the separate current-caller/global-Account/token guards for exact metadata and cleanup recovery. Current-token verification alone grants no admission. Forward V1014 stores separate immutable resolution of a retained unknown-decision abort without rewriting its original terminal evidence. Forward V1015 adds a disjoint never-admitted negative resolution, retaining the original transition, abandonment and candidate/closure digests without a binding decision; the linked lease contract owns its exact selectors and authority. Focused actual Account–Game Session composition covers that exact recovery and restart boundary; upstream source custody and test PKI remain controlled. Broader token-retirement and orphan-cleanup delivery, default registration and admitted binding remain unqualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) owns the implementation and proof details. @@ -54,7 +54,7 @@ The source preparation also includes unregistered, caller-transaction-bound crea Account's actor-staging eligibility owner read is a read-only, same-namespace Entity workload RPC gated off by default. Under one repeatable-read Account transaction it verifies persisted Account UUID/provenance, current Account membership and pair authority, fresh Game Design tenant-source evidence, and the current membership event/checkpoint, then returns digest-sealed evidence scoped to `PUBLIC_PRODUCTION_STAGING_ONLY`. It reports an eligible or ineligible source snapshot but creates no membership, actor assignment, JOIN, PLAY, or gameplay admission. The staged foundation passed 43 focused Account tests and 92 shared-evidence tests with no failures or skips, plus source generation and Account integration-source compilation. PostgreSQL migration/persistence proof sources are included but physical PostgreSQL and live runtime execution remain unrun; the RPC is not runtime-ready or admission authority. -Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST/gRPC and the Account component of the current Account/profile-local and legacy tenant exports expose that persisted UUID through `AccountDto.id`; the mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and new registration audit payloads use the same UUID. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, the Account UUID in Account-issued JWT `sub`/`accountId` claims, and `ProfileDto.accountId` now carry the persisted UUID. Account's UUID-to-row resolver reads by that UUID and verifies its persisted provenance and source-row binding before returning the private numeric Account row used by local storage operations; that row is not an API identity. The REST-specific update DTO keeps the UUID path/body contract distinct from the internal update contract; this local future composition retains UUID internal/gRPC updates and exact UUID caller binding. Tenant IDs and profile tenant identifiers retain their current representation. This bounded Account change does not migrate every consumer: retained numeric Redis session records remain fail-closed, and full JWT profile/registry behavior and remaining receiver proof are still incomplete; see the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-account-uuid-receiving-preparation). The current export is still partial Account/profile-local data, not the canonical portable export. Focused repository and retained-row migration cases remain distinct from the current ordinary receiving proof recorded in that tracker; [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. +Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST/gRPC and the Account component of current Account/profile-local and legacy tenant exports expose that UUID through `AccountDto.id`; the mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and registration audit payloads use the same UUID. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, Account-issued JWT `sub`/`accountId` claims, and `ProfileDto.accountId` carry the persisted UUID. Account resolves UUIDs to private numeric rows only for local storage operations; the row is not an API identity. REST-specific update DTOs preserve the UUID path/body contract, and internal/gRPC updates and caller binding use UUIDs. Tenant IDs and profile tenant identifiers retain their current representation. The final ordinary receiving proof and its limits are recorded in the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). The current export remains partial Account/profile-local data, not the canonical portable export. [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. The account lifecycle state machine, global deletion preconditions, account-scoped versus tenant-scoped portable-data export split, separate safety-restriction lifecycles, hosting-billing authority, and future-marketplace `purchase_entitlement` substrate are the canonical target design. The current service has live identity/authentication, profile, external-link persistence, recovery/verification, payment, subscription, notification, and virtual-currency foundations, but lifecycle state transitions, genuine provider authentication, cross-service export, retained-record handling, complete account lock/platform-ban enforcement, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial. The current account export returns only Account and profile rows, the tenant export includes excessive global Account fields, and DeleteAccount preserves its JOIN and billing denials before failing closed without deleting child rows; AccountRepository retains its independent hard-delete guard. A complete retained-data lifecycle remains absent. Those behaviors directly conflict with [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and the bounded erasure workflow below. @@ -107,7 +107,7 @@ The unregistered canonical gameplay LOGIN primary-credential adapter reuses Acco ## Data Model -- `account` table stores username, password hash, email, and status flags for the global platform account, with an immutable unique non-nil `account_uuid`, its provenance, and the unchanged numeric source-row id added by V29. The numeric source-row id remains Account-local; registration and the Account portion of current Account-local exports expose the UUID as described in [Account API Contracts](./api-contracts.md). Player-bootstrap and ordinary authentication results, JWT account subjects/claims, and profile Account fields use the UUID; the numeric row remains private and is resolved only by Account. This does not establish full downstream receiver convergence; see [Account API Contracts](./api-contracts.md) and the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-account-uuid-receiving-preparation). +- `account` table stores username, password hash, email, and status flags for the global platform account, with an immutable unique non-nil `account_uuid`, its provenance, and the unchanged numeric source-row id added by V29. The numeric source-row id remains Account-local; registration and Account-local export projections expose the UUID as described in [Account API Contracts](./api-contracts.md). Player-bootstrap and ordinary authentication results, JWT Account subjects/claims, profile Account fields, shared context, and qualified downstream Account references use UUID identity; Account resolves it to a private numeric row only for local storage. Full token-profile/registry qualification and production activation remain held; see the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). - Target `profile` relationships are tenant-scoped and keyed exactly by `{accountId, tenantId}`; profile reads/writes require the corresponding membership and exact tenant filter. Any legacy account-only profile shape is implementation drift and must not authorize or expose a tenant relationship. - Target `achievement` relationships are tenant-scoped and keyed exactly by `{tenantId, accountId, achievementId}` (with any additional version/effect identity carried separately); the legacy “account and game” wording/shape is implementation drift because `game` is not an authority identifier. - Target `external_account` records link a server-verified canonical `{provider, issuer, subject}` to one global platform account without tenant scope. The current tenant-scoped, caller-asserted row shape is implementation drift. 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 5171304959..c11b77e97a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -484,7 +484,7 @@ Live Account authentication hashes and verifies passwords with `argon2-jvm` Argo The authentication owner-preparation component enforces the existing Account UUID/provenance/source-row owner at ordinary control-UI authentication, gameplay password authentication, verified-email OTP completion, and player-bootstrap issuance. After successful credential and lifecycle checks, issuance requires the existing UUID lookup to resolve back to the authenticated row before challenge consumption, signing, or session mutation. Missing, nil, inconsistent, or unavailable identity evidence returns `AUTH_UNAVAILABLE`; invalid-credential behavior remains separate. That component adds no Account UUID storage, mapping subsystem, schema, wire/profile transition, or downstream activation. The qualified owner-preparation checkpoint retained numeric authentication/bootstrap results and JWT Account claims; the published bootstrap-only credential and scope transitions are recorded below, followed by the current unpublished ordinary UUID receiving preparation. -Focused R1130 passes all 269 selected executions: 211 `AccountServiceImplTest` cases, 52 `AccountGrpcServiceTest` cases and six native application cases, with zero failures, errors or skips. `AccountServiceImplTest` covers the four issuance entry points against missing/nil UUID, missing provenance/source row, inconsistent source row, missing UUID lookup, different returned owner/UUID, and unavailable readback, with no signing, successful-challenge deletion, or session write on refusal. Positive and invalid-credential cases retain their current contracts; existing issuance fixtures explicitly supply test-owned persisted UUID associations. `AccountGrpcServiceTest` covers `AUTH_UNAVAILABLE` propagation for password and email-OTP receivers. `AccountApplicationIntegrationTest.ordinaryAuthenticationAndBootstrapPreservePersistedOwnerAndCurrentNumericContract` passes physical PostgreSQL/Redis registration-to-login/bootstrap proof with unchanged UUID provenance/source rows and numeric ordinary response/JWT assertions. Affected compilation, enabled Account main/test/integration static analysis, formatting and documentation checks pass. Consolidated receiving R1137 also runs the complete Account unit task: 1679 reported cases with zero failures/errors and four existing conditional trust-permission cases skipped, plus all six selected native application cases. Enabled affected main/test/integration analysis, formatting and documentation checks pass. Current published-head CI and fresh-image proof remain separate obligations. Full UUID issuance/shared-context/Account-profile/mail/Game Session/Social/Logging receiving qualification, retained-reference migration disposition, and canonical gameplay activation remain open. +Focused R1130 passes all 269 selected executions: 211 `AccountServiceImplTest` cases, 52 `AccountGrpcServiceTest` cases and six native application cases, with zero failures, errors or skips. `AccountServiceImplTest` covers the four issuance entry points against missing/nil UUID, missing provenance/source row, inconsistent source row, missing UUID lookup, different returned owner/UUID, and unavailable readback, with no signing, successful-challenge deletion, or session write on refusal. Positive and invalid-credential cases retain their current contracts; existing issuance fixtures explicitly supply test-owned persisted UUID associations. `AccountGrpcServiceTest` covers `AUTH_UNAVAILABLE` propagation for password and email-OTP receivers. `AccountApplicationIntegrationTest.ordinaryAuthenticationAndBootstrapPreservePersistedOwnerAndCurrentNumericContract` passes physical PostgreSQL/Redis registration-to-login/bootstrap proof with unchanged UUID provenance/source rows and numeric ordinary response/JWT assertions. Affected compilation, enabled Account main/test/integration static analysis, formatting and documentation checks pass. Consolidated receiving R1137 also runs the complete Account unit task: 1679 reported cases with zero failures/errors and four existing conditional trust-permission cases skipped, plus all six selected native application cases. Enabled affected main/test/integration analysis, formatting and documentation checks pass. These are historical owner-preparation results; later UUID receiving qualification and its runtime limits are recorded under [Ordinary UUID issuer and receiving](#ordinary-uuid-issuer-and-receiving). #### Player-bootstrap UUID credential profile @@ -492,7 +492,7 @@ The published #3352 credential boundary migrates only `PlayerBootstrapResult.acc R1140 passes the complete Account unit task: 1697 reported cases, zero failures/errors and four existing conditional trust-permission skips. Its selected native aggregate initially failed the new email-verification journey because the test omitted the verification URL; enabled integration analysis also found three nullable fixture reads. R1145 passes all six selected native application cases, zero failures/errors/skips, after explicit test-owned mail configuration and required-record/recipient handling. Enabled affected main/test/integration analysis, formatting and documentation checks pass. `AccountApplicationIntegrationTest.bootstrapUsesPersistedUuidAcrossPasswordOtpReadsAndInvalidationWhileOrdinaryLoginStaysNumeric` executes real registration, unchanged numeric ordinary login, password bootstrap, actual email verification and generated-email-OTP bootstrap, UUID JWT/result assertions, subsequent HTTP bootstrap reads, successful-challenge removal and physical Redis session invalidation with unchanged persisted Account UUID/provenance/source-row identity. Its external Game Session discovery response and mail delivery remain controlled fixtures. Receiving R1147 at `89adf8951db3` on the qualified owner-diagnostic parent `584c336b55d0` passes all 229 Account service cases and the actual registration/password/OTP/bootstrap/session-invalidation native case, with zero failures/errors/skips and enabled affected analysis, formatting and documentation checks. Later parent carries retain the verified retention test and observation entries; their source attribution remains separate from this bootstrap proof. This is focused local proof; unfiltered native service execution and published-source CI/review remain separate obligations. -This is credential/result profile convergence, not full bootstrap-journey identity convergence or full canonical registry/profile qualification. The separately qualified bootstrap-connect-scope artifact also uses UUID identity. The Account-to-Entity character-discovery Account wire remains numeric cross-boundary drift, not private Account storage provenance. Ordinary control-UI/gameplay JWTs, shared forwarding/signed-routing intake, Social self-or-tenant authorization and APIs, public admission and gameplay activation remain outside this transition and retain their existing status. +This historical credential/result profile transition did not itself complete full bootstrap-journey identity convergence or canonical registry/profile qualification. The separately qualified bootstrap-connect-scope artifact also uses UUID identity. At this source, the Account-to-Entity character-discovery Account wire remained numeric; the final ordinary receiving cohort below converts that downstream Account reference to UUID while keeping Account SQL keys private. Ordinary control-UI/gameplay JWTs, shared forwarding/signed-routing intake, Social self-or-tenant authorization and APIs, public admission and gameplay activation remain outside this bootstrap-only transition. #### Bootstrap-connect-scope UUID artifact @@ -500,13 +500,13 @@ The published #3352 scope boundary migrates the existing opaque `bootstrap-conne Consolidated receiving R1154 at `13172a776051` passes the complete Account unit task (1699 reported cases, zero failures/errors, four existing conditional trust-permission skips), all 223 Common Security unit cases, and all seven selected native Account application cases with zero failures/errors/skips. Enabled affected main/unit/native analysis, formatting and documentation checks pass. Shared `JwtClaimsTest` exercises strict artifact identity and existing routing-field checks; `AccountServiceImplTest` covers both producers, UUID claims with unchanged private retained-row/digest identity, reader/owner-availability distinction and existing JOIN/replay/error guards. `AccountApplicationIntegrationTest.browserAndControlledDirectScopesRetainUuidClaimsAndPrivateJoinRows` executes real Account/subscription/scope persistence, both producers, a controlled exact Game Session peer context through the real Account gRPC handler, fail-closed connect-token calls, and actual browser/direct retained JOIN operations and retries. Runtime target discovery and the peer context are controlled fixtures; transport and certificate-derived identity are not exercised by this composition. Existing gRPC peer/caller/target unit coverage also runs in the complete Account task. The unchanged Guild lifecycle postimages retain their earlier R1137 Social proof. This qualifies the local consolidated credential/result and scope-artifact boundary; published-head CI and broad review of the expanded scope remain separate obligations. Earlier #3352 review captures cover their original 13-file comparison and are not new-feature review proof. -Previously signed numeric scopes are rejected when presented to the strict reader. Retained scope rows, operation receipts and their existing replay guards are preserved, not rewritten or mapped. Clients must obtain fresh scope evidence through bounded rediscovery/reauthentication; this source does not deploy an issuance-quiescence/expiry window or claim old scopes remain usable. Within that published boundary, incoming numeric direct-text `PlayerExecutionContext.account_id` and Account-to-Entity character discovery remain explicit separate cross-boundary drift, not private Account row provenance. Full canonical token-registry/profile qualification, production custody and admission activation remain held. No production Game Session text-JOIN caller exists at this pin, so controlled direct RPC proof is not text-client end-to-end proof. +Previously signed numeric scopes are rejected when presented to the strict reader. Retained scope rows, operation receipts and their existing replay guards are preserved, not rewritten or mapped. Clients must obtain fresh scope evidence through bounded rediscovery/reauthentication; this source does not deploy an issuance-quiescence/expiry window or claim old scopes remain usable. At this published scope-artifact boundary, incoming numeric direct-text `PlayerExecutionContext.account_id` and Account-to-Entity character discovery were separate cross-boundary drift; the final ordinary receiving cohort below converts those Account identity carriers to UUID. Full canonical token-registry/profile qualification, production custody and admission activation remain held. No production Game Session text-JOIN caller exists at this pin, so controlled direct RPC proof is not text-client end-to-end proof. #### Account-owned response UUID projection The response-only Account source projects canonical persisted Account UUIDs in every explicit JOIN outcome and in profile GET/UPDATE, gRPC JSON and Account-local export responses. Private scope/operation/member identities, immutable digests, receipts and side effects retain their existing representation. JOIN owner projection follows transaction completion; unavailable owner evidence returns `AUTH_UNAVAILABLE` without rewriting a retained result. Profile projection validates tenant/owner coherence and rereads the full Account because its repository embeds only a partial owner. The [Account API contract](../../architecture/microservices/account-service/api-contracts.md) owns the response semantics. -Focused service/controller/gRPC cases and native PostgreSQL composition cover UUID responses, generated profile mapping, retained private rows, replay and owner readback refusal. R1189 qualifies the response projection; REST selector proof has its separate attribution. Incoming direct-text context, ordinary JWT identity and shared forwarding, Account-to-Entity discovery, canonical tenant-qualified profile routes/authorization, token registry qualification and gameplay activation remain separate gaps. No production Game Session text-JOIN caller is introduced, and the unavailable JOIN route remains absent from public OpenAPI. +Focused service/controller/gRPC cases and native PostgreSQL composition cover UUID responses, generated profile mapping, retained private rows, replay and owner readback refusal. R1189 qualifies the response projection; REST selector proof has its separate attribution. At that source, incoming direct-text context, ordinary JWT identity/shared forwarding and Account-to-Entity discovery remained separate gaps; the final ordinary receiving cohort subsequently qualifies those UUID boundaries. Canonical tenant-qualified profile routes/authorization, token registry qualification and gameplay activation remain separate gaps. No production Game Session text-JOIN caller is introduced, and the unavailable JOIN route remains absent from public OpenAPI. R1189 passes the complete Account unit task (1,697 passed, zero failures/errors and four existing conditional trust-permission skips) and all seven native application cases without failures or skips. The native suite imports a distinctly named build-time copy of the canonical main application configuration and verifies its actual HTTP policy and interceptor, then exercises genuine ordinary-JWT profile HTTP access alongside JOIN/replay and profile/export projection with retained private SQL rows. Enabled main/unit/native analysis, formatting and documentation checks pass. Controlled test PKI/server overrides, private port-zero gRPC and workload namespace `test` remain component fixtures, not production PKI or namespace qualification. This is focused component and HTTP proof; full native-service execution, current published-head CI and production activation remain separate obligations. @@ -520,11 +520,11 @@ Local receipt of the REST selector source preserves the future UUID ordinary iss #### Ordinary Account UUID receiving preparation -The local reconstructed #2972 source converges ordinary password and verified-email OTP issuance, JWT subject/account binding, shared session intake/forwarding, typed Account internal/gRPC inputs, supported Social consumers/storage and Game Session LOGIN/PLAY/session carriers on persisted canonical Account UUIDs. Account alone resolves its UUID to a private row through persisted owner/provenance checks. Logging moderation and Entity roster selectors converge with PLAY; tenant identifiers retain their current numeric representation. The [Account identity contract](../../architecture/microservices/account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity) owns representation and owner resolution. This remains unpublished composition, with final receiving proof pending; the original donor and full final postimages are retained in the controller source record. +The final ordinary receiving source converges password and verified-email OTP issuance, JWT subject/account binding, shared session intake/forwarding, typed Account internal/gRPC inputs, supported Social consumers/storage and Game Session LOGIN/PLAY/session carriers on persisted canonical Account UUIDs. Profile `SessionContext` self-binding and global REST caller proof also use UUID identity; Account alone resolves UUIDs to private rows through persisted provenance checks. Logging moderation and Entity roster selectors converge with PLAY; tenant identifiers retain their current numeric representation. The [Account identity contract](../../architecture/microservices/account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity) owns representation and owner resolution. R1251 qualifies the actual Account-issued UUID credential through real intake composition. Final receiving proof and its boundaries are recorded below. -The earlier complete composition has separately attributed proof: R1228 passes 2,840 Game Session units, 22 WebSocket cases, 145 Social units, 16 Social native cases and eight Account native cases, but its aggregate fails Account test compilation. R1230 recovers the corrected Account suite with 1,797 passes and four existing conditional skips, plus affected test analysis/formatting. These are predecessor-source results, not a clean aggregate or current reconstructed-head qualification. Current Social V1003 and Logging V1003 follow their effective shared-saga V1002 parents; R1235 passes seven Social physical PostgreSQL cases, and R1239 passes two Logging physical cases plus generation, parent-aware ordering and affected analysis/formatting. Both migrations lock affected tables, refuse populated legacy references and preserve rows/history without guessed mappings, deletion or backfill. +Earlier composition runs remain separately attributed: R1228 passes 2,840 Game Session units, 22 WebSocket cases, 145 Social units, 16 Social native cases and eight Account native cases, but its aggregate fails Account test compilation; R1230 recovers the corrected Account suite with 1,797 passes and four existing conditional skips, plus affected test analysis/formatting. They are predecessor-source history, not the final qualification. Current Social V1003 and Logging V1003 follow their effective shared-saga V1002 parents; R1235 passes seven Social physical PostgreSQL cases, and R1239 passes two Logging physical cases plus generation, parent-aware ordering and affected analysis/formatting. Both migrations lock affected tables, refuse populated legacy references and preserve rows/history without guessed mappings, deletion or backfill. -Temporary preparation in #3359/#3360 may reject parent-issued numeric credentials or non-smoke consumer operations. #2972 owns genuine UUID issuer-to-consumer qualification and restoration of its preserved Profile/internal DTO, native Account and complete transport/item/communication proof postimages. Final supported behavior and retention/security constraints must remain intact. Privileged numeric realm-grant inputs, legacy numeric LogEvent/PlayerReport persistence, numeric deletion-client contracts and the legacy StartSession owner boundary remain separate tracked drift. Full JWT profile/registry qualification, default registration, source custody/PKI, public admission/activation/first OPEN and original NEW recovery holds remain unchanged; Redis absence supplies no provenance. +The final receiving composition restores its preserved Profile/internal DTO and native Account, transport/item/communication postimages. Separate drift remains in privileged numeric realm-grant inputs, legacy numeric LogEvent/PlayerReport persistence, numeric deletion-client contracts and the legacy numeric GameInstance owner/StartSession boundary. Full JWT profile/registry qualification, default registration, source custody/production PKI, public admission/activation/first OPEN and original NEW recovery holds remain unchanged; Redis absence supplies no provenance. The real Game Logic-to-Social `SendMessage` caller still uses workload-only authentication without an authenticated sender binding and therefore fails closed at the strict Social receiver. Controlled `SocialGroupsStubServer` transport cases do not establish real Social acceptance. This remains part of the existing [chat writer authorization and replay gaps](../../architecture/microservices/social-groups-service/api-contracts.md#implementation-status); UUID convergence supplies no internal impersonation grant or player-safe chat claim. @@ -532,7 +532,7 @@ The real Game Logic-to-Social `SendMessage` caller still uses workload-only auth The local final composition validates all five AccountController selectors as canonical persisted UUIDs and binds self/global-role callers before private owner resolution. Tenant export retains its tenant selector and current tenant-access policy. Profile GET/PUT similarly bind the UUID caller before owner SQL, enforce PUT path/body equality and correlate returned Account/tenant identity. Factor-update 501, deletion retention/business-rule denials and unavailable-owner error semantics remain. Canonical tenant-qualified routes, scoped-role/membership-generation qualification and full export lifecycle are separate gaps; representation changes grant no authority. The [Account API](../../architecture/microservices/account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity) owns the contract. -PR #3356's completed reviews and exact-head CI qualify its narrower response/REST-selector boundary with then-numeric ordinary intake. Its native proof remains attributed to that source. The reconstructed #2972 preserves the final UUID issuer, internal inputs and genuine native credential/HTTP composition; it does not inherit current-code qualification from #3356 or from #3360's controlled preparation callers. Final receiving qualification remains pending, with historical source/proof retained in controller records. +PR #3356's completed reviews and exact-head CI qualify only its narrower response/REST-selector boundary with then-numeric ordinary intake; that proof remains attributed to its source. The final UUID receiving qualification is independently recorded below and does not inherit proof from #3356 or controlled preparation callers. #### Social UUID receiver preparation @@ -542,7 +542,7 @@ Account owns canonical identity and owner resolution; Social consumes that ident The local receiving source converges ordinary password/verified-email credentials, UUID subject/account binding, shared intake/forwarding, Account owner reads, gameplay LOGIN/PLAY/context carriers, moderation selectors and ordinary Entity roster ownership on actual canonical Account UUIDs. Account alone resolves its UUID to private storage identity. Durable communication rejection retains player error output through delivery and replay. No numeric fallback, guessed ownership or retained-data rewrite is supplied. Canonical identity and authorization remain with the [Account API](../../architecture/microservices/account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity), [JWT contract](../../architecture/system-architecture-jwt-and-token-contracts.md#jwt-claim-contract-normative) and owning service contracts. -Final UUID-positive Login/WebSocket live and recent presence, AFK/reconnect, Account-native and transport/item/communication/load proof postimages are preserved. Current focused qualification passes 41 Game Session native cases and complete Entity unit/native checks; original run attribution and failed/recovery aggregates remain in the review records. Real Account-authenticated Entity seeding and fresh-image LOGIN/PLAY/LOOK remain pending under the [Entity tracker](./gameplay-rules-entities-and-effects.md#ordinary-account-uuid-ownership). Controlled transport proof does not establish genuine Social sender-handoff acceptance or player-safe chat; the [Social API limits](../../architecture/microservices/social-groups-service/api-contracts.md#implementation-status) remain. +Final UUID-positive Login/WebSocket live and recent presence, AFK/reconnect, Account-native and transport/item/communication/load proof postimages are preserved. R1273 passes 462 Entity unit and 135 native cases, with no failures, errors or skips. R1274 uses fresh images for actual Account `Authenticate` to Entity UUID seeding and direct LOGIN/PLAY/LOOK, then verifies authenticated cleanup leaves zero resources; this runtime proof is at `671a9e3e205ce39300b93aea03871efe890c5549`. R1279 exercises the actual certificate-derived mTLS receiver through the Entity service, mapper and PostgreSQL: positive, wrong-owner, wrong-tenant, unresolved-owner, wrong-service and wrong-namespace cases all pass. The final tree at `026c549985ccf5c461dba0ab8c026f525ce7014a` exactly matches the fully qualified source tree at `81fcde7c4049b0be4aa67c1b09f5d4c68db667f2`; only work partitioning differs. These focused results do not qualify the whole pipeline, production PKI, public admission, or current remote CI. Controlled Social transport proof still does not establish genuine Social sender-handoff acceptance or player-safe chat; the [Social API limits](../../architecture/microservices/social-groups-service/api-contracts.md#implementation-status) remain. Legacy numeric GameInstance owner/StartSession authorization and its numeric common owner helper remain separate unqualified drift; UUID callers are never equated with private numeric owner rows. Authorized tenant access is checked independently on instance reads/control. Production custody, registry/profile qualification, default registration, gameplay admission and activation holds remain unchanged. From 0ad5016a0bde9215020480458b1b653228667d6a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 11:29:37 +1300 Subject: [PATCH 19/34] fix: complete UUID discovery, policy batches and attestation issuance --- .../account-service/api-contracts.md | 4 +- .../api-contracts.md | 2 +- .../gameplay-rules-entities-and-effects.md | 2 +- .../client/EntityManagementClient.java | 8 +- .../repository/AccountRepository.java | 27 ++++++ .../service/AccountService.java | 3 + .../service/impl/AccountGrpcService.java | 28 +++--- .../service/impl/AccountServiceImpl.java | 58 ++++++++++++- .../AccountRepositoryIntegrationTest.java | 29 +++++++ .../client/EntityManagementClientTest.java | 87 +++++++++++++++++++ .../service/impl/AccountGrpcServiceTest.java | 54 +++++++----- .../service/impl/AccountServiceImplTest.java | 69 ++++++++++++++- .../GameplaySessionAttestationService.java | 4 +- ...GameplaySessionAttestationServiceTest.java | 34 ++++++++ .../stubs/EntityManagementStubServerTest.java | 29 +++++++ 15 files changed, 391 insertions(+), 47 deletions(-) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/EntityManagementClientTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index edf6285168..34adf67b1c 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -98,6 +98,8 @@ The account lifecycle API, export surfaces, and deletion-precondition contracts The implemented legacy profile REST handlers and five global Account REST handlers listed under [REST APIs](#rest-apis) accept only canonical lowercase non-nil Account UUID selectors. Account resolves them through `resolveAccountStorageId(UUID)`, including persisted provenance and source-row validation, before passing private numeric keys to existing Account-local services. Malformed, numeric, nil, uppercase or otherwise noncanonical selectors, and profile PUT path/body mismatches, are invalid arguments; inconsistent or unavailable owner evidence returns `AUTH_UNAVAILABLE`. A well-formed selector with no Account owner returns the same `403 PERMISSION_DENIED` and generic `Account access required` message as an existing owner the caller cannot access. Endpoint-specific authorization and status consequences remain below. +First-party bootstrap character discovery sends the authenticated bootstrap context's canonical Account UUID to Entity Management; Account's private storage key remains local. Entity's [ordinary ownership contract](../entity-management-service/api-contracts.md#ordinary-account-ownership) owns the receiver's same-namespace workload authorization and UUID-selected roster predicates. + The final ordinary receiving composition carries UUID ordinary JWT subjects/Account claims, UUID shared forwarding and UUID internal Account selectors, keeping numeric SQL rows private to Account. Profile `SessionContext` self-binding and global REST caller proof use that same UUID identity. Tenant identifiers remain numeric. Full token-profile/registry qualification, canonical tenant-scoped profile routes, complete portable or tenant-wide exports, production credential custody, public JOIN exposure and gameplay activation remain unqualified. Implementation and focused proof limits belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). ### Current vs Target Export Lifecycle @@ -134,7 +136,7 @@ In the ordinary Account gRPC methods, Account-valued selectors and authenticatio - `GetProfile` – retrieves the caller's profile relationship through canonical `GET /tenants/{tenantId}/profiles/{accountId}`, classified `tenant_regular`. Caller subject, scoped-role, and membership-generation validation follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. - `UpdateProfile` – modifies the caller's profile relationship through canonical `PUT /tenants/{tenantId}/profiles/{accountId}` under the same `tenant_regular` authorization and caller-subject binding. Membership authority follows [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the local API triggers notification emails. The response projection returns `PRIVATE` for a retained legacy `HIDDEN_STAFF` value without rewriting the stored row; normative policy remains in [ADR 0046](../../decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). The legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. -- `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 account IDs. Social projections consume this authority at read time; unknown or unavailable entries are intentionally omitted so callers apply complete `PRIVATE` redaction. +- `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. Account resolves known subjects through one local UUID batch query with the same persisted provenance and source-row checks as scalar identity reads, then returns policies keyed by UUID. Unknown or unproven entries are intentionally omitted so Social applies complete `PRIVATE` redaction. - `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current implementation behind this method remains the local legacy export described above. - `CommitTenantCapacityAdmission` – **target-state internal RPC** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by `GetTenantEntitlementsForRuntime` including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. Stale evidence, exhausted quota, unavailable authority, malformed identity, and conflicting retries fail closed. No proto RPC, caller integration, durable usage ledger, or reservation lifecycle is implemented yet. See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact attempt-and-fence retries replay; a changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index b9c83cb759..184e73603e 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -73,7 +73,7 @@ curl http://localhost:8080/ping - `CreateCharacter(CreateCharacterRequest) returns (CreateCharacterResponse)` – Current behavior: the scalar-only request validates tenant, account, and scope, then Entity returns an application `FAILED_PRECONDITION` before `CharacterService` allocation because the request cannot carry the authenticated owner proof and durable operation binding. Target behavior remains Entity-owned allocation and persistence of a primary controllable actor after the caller has passed Account membership/grant/realm admission. The target request carries the resolved `{accountId, tenantId, worldSlug, realmSlug}`, stable `playableStateNamespaceId`, the `playableStateScope` supplied only as authoritative realm-snapshot/attestation evidence, active `gameInstanceId`, explicit `entryPolicy=PLAYER_CREATED`, exact published descriptor identity/version, player creation input, and proof of the catalog/admission-pointer snapshot. Entity rejects a missing or mismatched policy before allocation or replay, and cross-checks the policy against the canonical snapshot and the applicable descriptor identity/version. It also carries caller-stable `createCharacterRequestId` and canonical `mutationDigest`; Entity recomputes the digest over the immutable trusted target, `entryPolicy`, exact descriptor/version, and creation input. The durable operation guard key is `{tenantId, playableStateNamespaceId, accountId, createCharacterRequestId}`. Within one local transaction, Entity admits and locks that guard plus digest, serializes the `PLAYER_CREATED` zero-roster boundary on `{tenantId, playableStateNamespaceId, accountId}`, and rereads the roster against the unchanged policy and descriptor/version before allocation. Only a still-empty roster may allocate; concurrent distinct request identities cannot both cross a stale zero-roster observation. Entity then atomically persists the allocated `{accountId, tenantId, playableStateNamespaceId, characterId}` association and replayable response. The same guard and digest exact-replay the original response; the same guard with a different digest returns `IDEMPOTENCY_CONFLICT` before allocation. Callers cannot choose or derive `playableStateScope`; Entity must reject caller-derived evidence and validate the exact immutable namespace/scope pair. A scope change under one namespace is rejected and never creates a second or split actor record. Entity allocates `characterId` only after the operation guard, validates the namespace/scope and active-instance fence, and never derives identity from account/name/hash or delegates character ownership to Account. Durable persistence/keying remains `{tenantId, playableStateNamespaceId, characterId}`; `playableStateScope` remains separately validated immutable routing/authorization evidence, `gameInstanceId` is only the replaceable active-runtime fence, and neither is a durable character-identity dimension. Entity Management does not expose a direct player REST route. This target boundary remains an implementation/proof gap; current implementation proves denial only. - `UpdateEntity(UpdateEntityRequest) returns (UpdateEntityResponse)` – updates mutable character state for the requested `{tenantId, playableStateNamespaceId, gameInstanceId, playableStateScope, characterId}` target. `playableStateScope` must be the authoritative realm-snapshot/attestation result; callers cannot choose or derive it, and Entity validates the exact immutable namespace/scope pair before mutation. A caller-selected or changed scope, missing/mismatched namespace or scope, stale snapshot, caller-asserted instance, or global `characterId` is rejected rather than updating or splitting records. Target state also requires a fresh, server-resolved active-instance authorization fence for that exact namespace/scope and instance, checked atomically immediately before mutation. The current request path does not yet carry and prove the complete fresh fence, so it remains an implementation/proof gap and must not be treated as target enforcement. - `QueryInventory(QueryInventoryRequest) returns (QueryInventoryResponse)` – the current response is an unpaged repeated `InventoryItem items[]` projection. The live handler emits `item_id`, `item_name`, `item_description`, and `quantity`, and conditionally emits `container_instance_id`, `item_instance_id`, and `visible_ref` when those values are present. This projection does not establish complete instance-aware identity or stack/concurrency safety: rich pagination, complete holder-local stack uniqueness, find-then-create concurrency, and explicit-family duplicate handling remain target/proof gaps documented in [Runtime and Data](./runtime-and-data.md#implementation-status). -- `ListCharactersByAccount` (broader target-state policy/descriptor/template/namespace behavior) – the eventual policy-aware roster contract returns only persisted actors valid for the trusted account selector and resolved `{tenantId, playableStateNamespaceId, playableStateScope}` target. Entity validates account-to-character ownership; account identity is ownership evidence, not controller identity. The target response includes the exact published v1 entry policy and only its applicable versioned identity: descriptor/version for `PLAYER_CREATED`, template/version for `AUTO_PROVISIONED`, neither for `PRESEEDED_ONLY`; it echoes namespace/scope and returns an immutable roster snapshot identity/digest for the exact target, policy/version, and ordered roster. `gameInstanceId` is a fresh active-runtime fence, not durable lookup identity. Zero, one, and many results follow policy-specific next actions; a roster is discovery evidence, not admission authority. The separate `CanonicalGameplayRosterService` wire above specifies the existing `PRESEEDED_ONLY` branch and the distinct, unregistered `PLAYER_CREATED` methods `ListPlayerCreatedRoster` and `ReadSelectedPlayerCreatedCharacter`. `AUTO_PROVISIONED` remains a later-owned target branch, and the legacy numeric `ListCharactersByAccount` method is not trusted for canonical gameplay. Current handlers do not prove these target contracts. +- `ListCharactersByAccount` (broader target-state policy/descriptor/template/namespace behavior) – the eventual policy-aware roster contract returns only persisted actors valid for the trusted account selector and resolved `{tenantId, playableStateNamespaceId, playableStateScope}` target. Entity validates account-to-character ownership; account identity is ownership evidence, not controller identity. The target response includes the exact published v1 entry policy and only its applicable versioned identity: descriptor/version for `PLAYER_CREATED`, template/version for `AUTO_PROVISIONED`, neither for `PRESEEDED_ONLY`; it echoes namespace/scope and returns an immutable roster snapshot identity/digest for the exact target, policy/version, and ordered roster. `gameInstanceId` is a fresh active-runtime fence, not durable lookup identity. Zero, one, and many results follow policy-specific next actions; a roster is discovery evidence, not admission authority. The separate `CanonicalGameplayRosterService` wire above specifies the existing `PRESEEDED_ONLY` branch and the distinct, unregistered `PLAYER_CREATED` methods `ListPlayerCreatedRoster` and `ReadSelectedPlayerCreatedCharacter`. `AUTO_PROVISIONED` remains a later-owned target branch, and the current ordinary UUID-valued `ListCharactersByAccount` method is not trusted for canonical gameplay. Current handlers do not prove these target contracts. - `AutoProvisionCharacter` (target-state) – after explicit entry, idempotently provisions at most one actor from the published realm template using the trusted `{tenantId, accountId, playableStateNamespaceId}` as the at-most-one uniqueness tuple. The request carries explicit `entryPolicy=AUTO_PROVISIONED`, the unchanged discovered-entry object and `discoveredEntryDigest`, the applicable exact template identity/version, a caller-stable `autoProvisionRequestId` that is stable and unique only within that exact `{tenantId, accountId, playableStateNamespaceId}` target scope, canonical `mutationDigest`, and an explicit absent-creation-input marker following ADR 0140's fixed-position presence encoding. Entity rejects a missing or mismatched policy before allocation or replay, and cross-checks it against the canonical snapshot and applicable template identity/version. Entity recomputes the mutation digest over the immutable trusted target, `entryPolicy`, exact template identity/version, and absent-input marker, and durably guards the operation by `{tenantId, accountId, playableStateNamespaceId, autoProvisionRequestId}` separately from the at-most-one-actor constraint; these operation-guard and actor-uniqueness constraints remain distinct. An actor-uniqueness race between distinct request IDs has one winner; each loser transactionally rereads and validates the exact target, policy, template provenance, and digest, durably stores its own guard result, and returns/replays the same actor only on exact match. A loser with mismatched provenance or digest stores a terminal `IDEMPOTENCY_CONFLICT` outcome and never replaces or allocates another actor. `playableStateScope` is only server-validated routing/authorization-fence evidence and is not an alternate key; `gameInstanceId` is the replaceable active-runtime fence. The same target-scoped guard with the same digest exact-replays the persisted actor, including under concurrent delivery; the same scoped guard with a changed digest-bound intent returns `IDEMPOTENCY_CONFLICT` before allocation. A different tenant, account, or namespace selects a different target-scoped guard and must not conflict solely because the text request ID is reused; no global request registry is implied. The current surface and proof are not implemented. - `QueryActorState` – returns gameplay-attested actor resources and active conditions for a scoped character. - `ApplyActorCondition` – **target-state request:** applies a gameplay-attested active condition or transient action state for a scoped character. The canonical target request carries a dedicated operation-unique `effectId`, separate source provenance, optional expiry, and the exact release-pinned typed effect declaration/reference and digest resolved by the server-side gameplay path; caller-defined effect JSON is not mutation authority. The target mutation persists the frozen definition/release and its server-resolved typed applied-effect snapshot and digest, never a caller-supplied payload. The current request still accepts transitional `effectPayloadJson`, so this typed-plan/no-caller-payload boundary is not live enforcement yet. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index fd077ad43a..afa7f1f970 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -108,7 +108,7 @@ These links add decision provenance only; they do not upgrade entity, equipment, | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata and prepared ordinary Account UUID storage/nested-copy carriers, exact canonical identity readers, assignment/receipt/roster storage, an unregistered created-actor terminal writer and source-bound roster/receipt consumers, and manually composed unregistered source services and guarded read-client/adapter definitions are present. Legacy consumers retain develop behavior for legacy rows; new owner-resolved actors are excluded from numeric character and holder predicates. The authenticated assignment handler and caller remain manually composed and unregistered; retained-identity promotion, controller/execution replacement and production admission remain unavailable. The bounded preseeded and PLAYER_CREATED runtime projections and their separate purpose-specific reference reads are present; generic actor runtime and replacement remain incomplete. | `proven` - bounded passive preparation and controlled-storage proof for created-actor capture/readback, sealed-roster retention, exact canonical actor-repository read isolation, and passive ordinary Account UUID storage/copy owner isolation. See [Player-created owner and roster preparation](#player-created-owner-and-roster-preparation). See [Canonical sealed roster retention prerequisite](#canonical-sealed-roster-retention-prerequisite), [Canonical actor repository read isolation](#canonical-actor-repository-read-isolation) and [Validation and Proof](#validation-and-proof). See [Protected preseeded assignment ingress](#protected-preseeded-assignment-ingress); this proof does not establish genuine owner issuance, production registration or runtime activation, public admission, or a packaged player journey. The bounded runtime-reference owner/security units and selected Entity PostgreSQL receiving suites pass within R981, whose aggregate remains failed on the separate Game Session membership fixture and frontier/static checks; complete-suite and production limits remain. The distinct PLAYER_CREATED proof passes three Entity ingress units and 22 native creation/projection/mTLS cases in R840, with Entity static recovery in R842. R882/R883 supply receiving proof with their original failed aggregates and separate R884 static recovery. R898 adds 20 staged receiving cases on the reconciled parent for the bounded PLAYER_CREATED projection/reference, World receiving and Game Session region-consumer components, including retention of the first timeline across a later actor’s fresh region grant. Their scopes and limits are attributed by the [Player Access tracker](./player-access-and-session.md#canonical-new-admission-components); those historical results do not qualify a newer head. Current R1128 receiving checks for uniform refusal and independent historical digest proof pass as recorded in [Validation and Proof](#validation-and-proof). | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql); [CanonicalGameplayRosterGrpcAdapter.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java); [CanonicalGameplayRosterPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java); [GameSessionCanonicalGameplayRosterOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java); [GameSessionPreseededActorAssignmentOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java); [CanonicalGameplayRosterRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java); [CanonicalGameplayRosterRecoveryService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryService.java); [CanonicalGameplayRosterRetentionService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java); [V1012 sealed-roster retention](../../../services/entity-management-service/src/main/resources/db/migration/V1012__canonical_roster_retention.sql); [CanonicalGameplayRosterReferenceOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java); [CanonicalGameplayRosterReferenceRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java); [V1015 roster reference owner](../../../services/game-session-service/src/main/resources/db/migration/V1015__canonical_roster_reference_owner.sql); [EntityCharacterCreateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java); [EntityPlayerCreatedRosterSnapshotRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java); [EntityPlayerCreatedRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java); [Entity V1015 character-create terminal](../../../services/entity-management-service/src/main/resources/db/migration/V1015__entity_character_create_terminal.sql); [Entity V1016 player-created roster snapshots](../../../services/entity-management-service/src/main/resources/db/migration/V1016__player_created_roster_snapshot_receipts.sql); [Entity V1020 typed created-retirement recognition](../../../services/entity-management-service/src/main/resources/db/migration/V1020__canonical_roster_created_retirement_recognition.sql); [Game Session V1020 player-created roster reference](../../../services/game-session-service/src/main/resources/db/migration/V1020__player_created_roster_reference.sql); [Entity V1014 retirement observation](../../../services/entity-management-service/src/main/resources/db/migration/V1014__canonical_roster_retirement_observation.sql); [Game Session V1017 retirement observation](../../../services/game-session-service/src/main/resources/db/migration/V1017__canonical_roster_retirement_observation.sql); [CanonicalGameplayRosterRetirementEvidence.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java); [CanonicalPreseededActorAssignmentGrpcService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcService.java); [CanonicalPreseededActorAssignmentPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptor.java); [PreseededActorAssignmentGrpcCodec.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodec.java); [PreseededActorAssignmentConfiguration.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfiguration.java); [CanonicalPreseededActorAssignmentClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClient.java); [V1018 staged retirement](../../../services/entity-management-service/src/main/resources/db/migration/V1018__canonical_roster_staged_retirement.sql); [V1019 snapshot retirement seals](../../../services/entity-management-service/src/main/resources/db/migration/V1019__canonical_roster_snapshot_retirement_seals.sql); [PreseededActorRuntimeProjectionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/PreseededActorRuntimeProjectionRepository.java); [V1022 runtime projection](../../../services/entity-management-service/src/main/resources/db/migration/V1022__preseeded_runtime_actor_projection.sql); [CanonicalPreseededActorRuntimeReferenceClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClient.java); [EntityPlayerCreatedRuntimeProjectionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeProjectionRepository.java); [EntityPlayerCreatedRuntimeReferenceService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeReferenceService.java); [Entity V1023 player-created runtime projection](../../../services/entity-management-service/src/main/resources/db/migration/V1023__player_created_runtime_projection.sql); [Entity V1024 ordinary Account UUID ownership](../../../services/entity-management-service/src/main/resources/db/migration/V1024__ordinary_account_uuid_owner.sql) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java); [CanonicalGameplayRosterConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java); [PreseededActorAssignmentConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java); [CanonicalGameplayRosterPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java); [CanonicalGameplayRosterGrpcAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java); [GameSessionCanonicalGameplayRosterOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java); [GameSessionPreseededActorAssignmentOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java); [AccountRuntimeIdentityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java); [AccountPreseededActorStagingEligibilityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java); [GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java); [GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java); [Entity retention PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java); [Entity recovery service unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java); [Entity retention sweep unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java); [Entity recovery adapter mTLS proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java); [Entity character-create PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java); [Entity player-created roster snapshot PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java); [Game Session reference PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java); [Player-created roster owner composition integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java); [Game Session reference mTLS proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java); [CanonicalPreseededActorAssignmentGrpcServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcServiceTest.java); [CanonicalPreseededActorAssignmentPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptorTest.java); [PreseededActorAssignmentGrpcCodecTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodecTest.java); [PreseededActorAssignmentIngressFactoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentIngressFactoryTest.java); [CanonicalPreseededActorAssignmentClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientTest.java); [CanonicalPreseededActorAssignmentClientMtlsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientMtlsTest.java); [PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java); [Canonical roster correction migration-ordering PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalRosterCorrectionMigrationOrderingPostgresIntegrationTest.java); [CanonicalPreseededActorRuntimeReferenceClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientTest.java); [CanonicalPreseededActorRuntimeReferenceClientMtlsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientMtlsTest.java); [EntityPlayerCreatedRuntimeReferenceIngressTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeReferenceIngressTest.java); [CanonicalPlayerCreatedRuntimeReferenceClientMtlsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRuntimeReferenceClientMtlsTest.java); [OrdinaryAccountUuidOwnerPostgresIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Authenticated owner provenance and genuine authority, full current supersession-to-retirement composition and genuine created-roster authority, real caller/controller/execution replacement, production admission, production PKI and activation, and a genuine playable journey remain open. Genuine policy/descriptor/template owner composition, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle also remain gaps. Ordinary UUID wire/service/DTO/seed receiving and actual Account-authenticated fresh-image smoke are qualified with their component and runtime limits in [Player Access](./player-access-and-session.md#ordinary-uuid-issuer-and-receiving); canonical actor promotion, registration and public admission remain held. The sealed-roster retention prerequisite is locally source- and proof-qualified but remains unregistered. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata and ordinary Account UUID storage, wire/service/DTO receiving, nested-copy carriers and Account-authenticated demo seeding, exact canonical identity readers, assignment/receipt/roster storage, an unregistered created-actor terminal writer and source-bound roster/receipt consumers, and manually composed unregistered source services and guarded read-client/adapter definitions are present. Legacy numeric owner rows remain retained without invented UUID projection; new owner-resolved actors remain excluded from numeric character and holder predicates. The authenticated assignment handler and caller remain manually composed and unregistered; retained-identity promotion, controller/execution replacement and production admission remain unavailable. The bounded preseeded and PLAYER_CREATED runtime projections and their separate purpose-specific reference reads are present; generic actor runtime and replacement remain incomplete. | `proven` - bounded passive preparation and controlled-storage proof for created-actor capture/readback, sealed-roster retention, exact canonical actor-repository read isolation, and ordinary Account UUID storage/receiver/copy owner isolation. See [Player-created owner and roster preparation](#player-created-owner-and-roster-preparation). See [Canonical sealed roster retention prerequisite](#canonical-sealed-roster-retention-prerequisite), [Canonical actor repository read isolation](#canonical-actor-repository-read-isolation) and [Validation and Proof](#validation-and-proof). See [Protected preseeded assignment ingress](#protected-preseeded-assignment-ingress); this proof does not establish genuine owner issuance, production registration or runtime activation, public admission, or a packaged player journey. The bounded runtime-reference owner/security units and selected Entity PostgreSQL receiving suites pass within R981, whose aggregate remains failed on the separate Game Session membership fixture and frontier/static checks; complete-suite and production limits remain. The distinct PLAYER_CREATED proof passes three Entity ingress units and 22 native creation/projection/mTLS cases in R840, with Entity static recovery in R842. R882/R883 supply receiving proof with their original failed aggregates and separate R884 static recovery. R898 adds 20 staged receiving cases on the reconciled parent for the bounded PLAYER_CREATED projection/reference, World receiving and Game Session region-consumer components, including retention of the first timeline across a later actor’s fresh region grant. Their scopes and limits are attributed by the [Player Access tracker](./player-access-and-session.md#canonical-new-admission-components); those historical results do not qualify a newer head. Current R1128 receiving checks for uniform refusal and independent historical digest proof pass as recorded in [Validation and Proof](#validation-and-proof). | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [EntityManagementRequestReaders.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EntityManagementRequestReaders.java); [CharacterMapper.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java); [EntityManagementGrpcService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java); [TestDataSeeder.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/data/TestDataSeeder.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql); [CanonicalGameplayRosterGrpcAdapter.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java); [CanonicalGameplayRosterPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java); [GameSessionCanonicalGameplayRosterOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java); [GameSessionPreseededActorAssignmentOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java); [CanonicalGameplayRosterRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java); [CanonicalGameplayRosterRecoveryService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryService.java); [CanonicalGameplayRosterRetentionService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java); [V1012 sealed-roster retention](../../../services/entity-management-service/src/main/resources/db/migration/V1012__canonical_roster_retention.sql); [CanonicalGameplayRosterReferenceOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java); [CanonicalGameplayRosterReferenceRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java); [V1015 roster reference owner](../../../services/game-session-service/src/main/resources/db/migration/V1015__canonical_roster_reference_owner.sql); [EntityCharacterCreateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java); [EntityPlayerCreatedRosterSnapshotRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java); [EntityPlayerCreatedRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java); [Entity V1015 character-create terminal](../../../services/entity-management-service/src/main/resources/db/migration/V1015__entity_character_create_terminal.sql); [Entity V1016 player-created roster snapshots](../../../services/entity-management-service/src/main/resources/db/migration/V1016__player_created_roster_snapshot_receipts.sql); [Entity V1020 typed created-retirement recognition](../../../services/entity-management-service/src/main/resources/db/migration/V1020__canonical_roster_created_retirement_recognition.sql); [Game Session V1020 player-created roster reference](../../../services/game-session-service/src/main/resources/db/migration/V1020__player_created_roster_reference.sql); [Entity V1014 retirement observation](../../../services/entity-management-service/src/main/resources/db/migration/V1014__canonical_roster_retirement_observation.sql); [Game Session V1017 retirement observation](../../../services/game-session-service/src/main/resources/db/migration/V1017__canonical_roster_retirement_observation.sql); [CanonicalGameplayRosterRetirementEvidence.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java); [CanonicalPreseededActorAssignmentGrpcService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcService.java); [CanonicalPreseededActorAssignmentPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptor.java); [PreseededActorAssignmentGrpcCodec.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodec.java); [PreseededActorAssignmentConfiguration.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfiguration.java); [CanonicalPreseededActorAssignmentClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClient.java); [V1018 staged retirement](../../../services/entity-management-service/src/main/resources/db/migration/V1018__canonical_roster_staged_retirement.sql); [V1019 snapshot retirement seals](../../../services/entity-management-service/src/main/resources/db/migration/V1019__canonical_roster_snapshot_retirement_seals.sql); [PreseededActorRuntimeProjectionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/PreseededActorRuntimeProjectionRepository.java); [V1022 runtime projection](../../../services/entity-management-service/src/main/resources/db/migration/V1022__preseeded_runtime_actor_projection.sql); [CanonicalPreseededActorRuntimeReferenceClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClient.java); [EntityPlayerCreatedRuntimeProjectionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeProjectionRepository.java); [EntityPlayerCreatedRuntimeReferenceService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeReferenceService.java); [Entity V1023 player-created runtime projection](../../../services/entity-management-service/src/main/resources/db/migration/V1023__player_created_runtime_projection.sql); [Entity V1024 ordinary Account UUID ownership](../../../services/entity-management-service/src/main/resources/db/migration/V1024__ordinary_account_uuid_owner.sql) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java); [CanonicalGameplayRosterConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java); [PreseededActorAssignmentConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java); [CanonicalGameplayRosterPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java); [CanonicalGameplayRosterGrpcAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java); [GameSessionCanonicalGameplayRosterOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java); [GameSessionPreseededActorAssignmentOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java); [AccountRuntimeIdentityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java); [AccountPreseededActorStagingEligibilityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java); [GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java); [GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java); [Entity retention PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java); [Entity recovery service unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java); [Entity retention sweep unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java); [Entity recovery adapter mTLS proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java); [Entity character-create PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java); [Entity player-created roster snapshot PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java); [Game Session reference PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java); [Player-created roster owner composition integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java); [Game Session reference mTLS proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java); [CanonicalPreseededActorAssignmentGrpcServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcServiceTest.java); [CanonicalPreseededActorAssignmentPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptorTest.java); [PreseededActorAssignmentGrpcCodecTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodecTest.java); [PreseededActorAssignmentIngressFactoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentIngressFactoryTest.java); [CanonicalPreseededActorAssignmentClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientTest.java); [CanonicalPreseededActorAssignmentClientMtlsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientMtlsTest.java); [PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java); [Canonical roster correction migration-ordering PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalRosterCorrectionMigrationOrderingPostgresIntegrationTest.java); [CanonicalPreseededActorRuntimeReferenceClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientTest.java); [CanonicalPreseededActorRuntimeReferenceClientMtlsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientMtlsTest.java); [EntityPlayerCreatedRuntimeReferenceIngressTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeReferenceIngressTest.java); [CanonicalPlayerCreatedRuntimeReferenceClientMtlsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRuntimeReferenceClientMtlsTest.java); [OrdinaryAccountUuidOwnerPostgresIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java); [EntityManagementGrpcServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java); [CharacterControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/CharacterControllerTest.java); [TestDataSeederTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/data/TestDataSeederTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Authenticated owner provenance and genuine authority, full current supersession-to-retirement composition and genuine created-roster authority, real caller/controller/execution replacement, production admission, production PKI and activation, and a genuine playable journey remain open. Genuine policy/descriptor/template owner composition, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle also remain gaps. Ordinary UUID wire/service/DTO/seed receiving and actual Account-authenticated fresh-image smoke are qualified with their component and runtime limits in [Player Access](./player-access-and-session.md#ordinary-uuid-issuer-and-receiving); canonical actor promotion, registration and public admission remain held. The sealed-roster retention prerequisite is locally source- and proof-qualified but remains unregistered. | | GR-3.2 Inventory, containers, ownership, and placement | `partial` - item instances/stacks, hidden and room-ground containers, guarded transfers, visible refs, audits, and replay guards for nonblank `effectId` are live; blank-`effectId` compatibility execution bypasses the Entity replay ledger. | `proven` - focused inventory, container, stack, transfer, location, and nonblank-`effectId` mutation-replay tests cover the bounded holder model; blank-ID ingress bypass and remediation proof remain open. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Blank-`effectId` replay-ledger bypass and its ingress remediation remain open, alongside nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting. | | GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - authored slot/body-layout compatibility and `WEAR`/`REMOVE` equipment binding are live; loadouts and lifecycle triggers are not. | `proven` - focused equipment service/controller and item-command tests cover slot compatibility and binding. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, and owner-validated cutover remapping remain target gaps coordinated with AR-3.2. | | GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - typed actor-state evaluation, conditions, durable replay, and self-targeted `APPLY_ACTION_STATE` admission are live; general action resolution is not. | `proven` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover the bounded seam. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/EntityManagementClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/EntityManagementClient.java index 7d1cc23282..f184c01306 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/EntityManagementClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/EntityManagementClient.java @@ -3,6 +3,7 @@ import jakarta.annotation.PostConstruct; import java.io.IOException; import java.util.List; +import java.util.UUID; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; @@ -52,13 +53,16 @@ protected EntityManagementServiceGrpc.EntityManagementServiceBlockingStub buildS } public List listCharactersByAccount( - long tenantId, long accountId, long gameInstanceId, PlayableStateScope playableStateScope) { + long tenantId, UUID accountUuid, long gameInstanceId, PlayableStateScope playableStateScope) { + if (accountUuid == null || accountUuid.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("A non-nil Account UUID is required"); + } ListCharactersByAccountResponse response = stub() .listCharactersByAccount( ListCharactersByAccountRequest.newBuilder() .setTenantId(Long.toString(tenantId)) - .setAccountId(Long.toString(accountId)) + .setAccountId(accountUuid.toString()) .setGameInstanceId(Long.toString(gameInstanceId)) .setPlayableStateScope(playableStateScope) .build()); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java index 4d9769a331..32df02bf99 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java @@ -3,6 +3,7 @@ import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNTS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -112,6 +113,32 @@ public Optional findByAccountUuid(UUID accountUuid) { .fetchOne(this::toEntity)); } + /** Reads the requested UUID rows with one query, omitting rows that fail scalar readback. */ + public List findByAccountUuids(List accountUuids) { + if (accountUuids == null || accountUuids.isEmpty()) { + return List.of(); + } + for (UUID accountUuid : accountUuids) { + if (accountUuid == null || accountUuid.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("A non-nil Account UUID is required"); + } + } + List records = + dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.ACCOUNT_UUID.in(accountUuids)).fetch(); + List accounts = new ArrayList<>(records.size()); + for (AccountsRecord record : records) { + try { + Account account = toEntity(record); + if (account != null) { + accounts.add(account); + } + } catch (IllegalArgumentException | IllegalStateException ex) { + // Scalar UUID resolution rejects this row; a batch omits only that subject. + } + } + return List.copyOf(accounts); + } + /** Locks one exact Account UUID inside a writable owner transaction. */ @Transactional(propagation = Propagation.MANDATORY) public Optional findByAccountUuidForUpdate(UUID accountUuid) { 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 75f526cda4..13795c7d9e 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 @@ -68,6 +68,9 @@ RuntimeMembershipDto getTenantMembershipForRuntime( /** Resolves the public Account UUID to its private numeric storage key inside Account only. */ Long resolveAccountStorageId(UUID accountUuid); + /** Resolves known, provenance-backed Account UUIDs to private storage keys in one local read. */ + java.util.Map resolveAccountStorageIds(java.util.List accountUuids); + RealmAccessGrantResult getRealmAccessGrantForRuntime( Long accountId, Long tenantId, String worldSlug, String realmSlug, String requestId); 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 c36eb6d482..abe1ce6bdd 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 @@ -757,16 +757,18 @@ public void listPresenceVisibilityPolicies( .map(AccountGrpcService::requireCanonicalAccountUuid) .distinct() .toList(); - java.util.Map storageIdsByAccountUuid = new java.util.LinkedHashMap<>(); + java.util.Map resolvedStorageIdsByAccountUuid = + accountService.resolveAccountStorageIds(accountUuids); + if (resolvedStorageIdsByAccountUuid == null) { + throw new IllegalStateException("Account UUID batch resolution returned no result"); + } java.util.Map accountUuidsByStorageId = new java.util.HashMap<>(); - for (UUID accountUuid : accountUuids) { - Long storageId; - try { - storageId = accountService.resolveAccountStorageId(accountUuid); - } catch (IllegalArgumentException | IllegalStateException ex) { - // Unknown or unproven local subjects are omitted so Social applies complete PRIVATE - // redaction rather than receiving a guessed identity or a private storage key. - continue; + for (java.util.Map.Entry resolution : + resolvedStorageIdsByAccountUuid.entrySet()) { + UUID accountUuid = resolution.getKey(); + Long storageId = resolution.getValue(); + if (accountUuid == null || !accountUuids.contains(accountUuid)) { + throw new IllegalStateException("Account UUID batch resolution returned an invalid row"); } if (storageId == null || storageId <= 0L) { continue; @@ -775,7 +777,13 @@ public void listPresenceVisibilityPolicies( if (previousAccountUuid != null && !previousAccountUuid.equals(accountUuid)) { throw new IllegalStateException("Account UUID resolution returned an ambiguous row"); } - storageIdsByAccountUuid.put(accountUuid, storageId); + } + java.util.Map storageIdsByAccountUuid = new java.util.LinkedHashMap<>(); + for (UUID accountUuid : accountUuids) { + Long storageId = resolvedStorageIdsByAccountUuid.get(accountUuid); + if (storageId != null && storageId > 0L) { + storageIdsByAccountUuid.put(accountUuid, storageId); + } } java.util.List storageIds = java.util.List.copyOf(storageIdsByAccountUuid.values()); java.util.Map policies = 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 591ca01481..c2e5e02b36 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 @@ -16,6 +16,7 @@ import java.util.Comparator; import java.util.HashMap; import java.util.HexFormat; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -514,12 +515,13 @@ public List listBootstrapCharacters( validateConnectScopeRoute(scopeContext, worldSlug, realmSlug); RuntimeRealmTarget realm = requireCurrentAdmissibleConnectScopeTarget(bootstrapContext, scopeContext); + UUID accountUuid = bootstrapContext.accountUuid(); + if (accountUuid == null || NIL_ACCOUNT_UUID.equals(accountUuid)) { + throw new IllegalStateException("Bootstrap Account UUID is unavailable"); + } return entityManagementClient .listCharactersByAccount( - realm.tenantId(), - bootstrapContext.accountId(), - realm.gameInstanceId(), - toPlayableStateScope(realm)) + realm.tenantId(), accountUuid, realm.gameInstanceId(), toPlayableStateScope(realm)) .stream() .sorted(Comparator.comparing(net.firedevops.firemud.entitymanagement.v1.Character::getName)) .map( @@ -2134,6 +2136,54 @@ public Long resolveAccountStorageId(UUID accountUuid) { accountRepository .findByAccountUuid(accountUuid) .orElseThrow(() -> new IllegalArgumentException("Account not found")); + return requireAccountStorageId(account, accountUuid); + } + + @Override + @Transactional(readOnly = true) + public Map resolveAccountStorageIds(List accountUuids) { + if (accountUuids == null) { + throw new IllegalArgumentException("Account UUIDs are required"); + } + List requestedAccountUuids = accountUuids.stream().distinct().toList(); + if (requestedAccountUuids.isEmpty()) { + return Map.of(); + } + if (requestedAccountUuids.stream() + .anyMatch(uuid -> uuid == null || NIL_ACCOUNT_UUID.equals(uuid))) { + throw new IllegalArgumentException("Canonical non-nil Account UUIDs are required"); + } + Map storageIdsByAccountUuid = new LinkedHashMap<>(); + Map accountUuidsByStorageId = new HashMap<>(); + for (Account account : accountRepository.findByAccountUuids(requestedAccountUuids)) { + UUID accountUuid = account == null ? null : account.getAccountUuid(); + if (accountUuid == null || !requestedAccountUuids.contains(accountUuid)) { + throw new IllegalStateException("Account UUID batch read returned an unexpected row"); + } + long storageId; + try { + storageId = requireAccountStorageId(account, accountUuid); + } catch (IllegalArgumentException | IllegalStateException ex) { + // The scalar caller omits this subject after the same failed owner readback. + continue; + } + UUID previousAccountUuid = accountUuidsByStorageId.putIfAbsent(storageId, accountUuid); + if (previousAccountUuid != null && !previousAccountUuid.equals(accountUuid)) { + throw new IllegalStateException("Account UUID resolution returned an ambiguous row"); + } + Long previousStorageId = storageIdsByAccountUuid.putIfAbsent(accountUuid, storageId); + if (previousStorageId != null && previousStorageId != storageId) { + throw new IllegalStateException("Account UUID resolution returned an ambiguous row"); + } + } + return Map.copyOf(storageIdsByAccountUuid); + } + + private long requireAccountStorageId(Account account, UUID accountUuid) { + if (account == null) { + throw new IllegalStateException( + "Account UUID readback did not match its exact persisted source row"); + } AccountIdentityProvenance provenance = account.getAccountUuidProvenance(); if (account.getId() == null || account.getId() <= 0L diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index 214a8d78ce..eb3bc68da2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -1292,6 +1292,35 @@ void repositoryPersistsAndReadsBackUniqueAccountUuidAndProvenance() { .isEqualTo(accountUuid); } + @Test + void batchAccountUuidReadReturnsOnlyRequestedRowsWithPersistedIdentityEvidence() { + Account first = + saveInTransaction( + account( + "batch-owner-one", "batch-owner-one@example.com", AccountLifecycleState.ACTIVE)); + Account second = + saveInTransaction( + account( + "batch-owner-two", "batch-owner-two@example.com", AccountLifecycleState.ACTIVE)); + + List owners = + repository.findByAccountUuids( + List.of(first.getAccountUuid(), UUID.randomUUID(), second.getAccountUuid())); + + assertThat(owners) + .extracting(Account::getAccountUuid) + .containsExactlyInAnyOrder(first.getAccountUuid(), second.getAccountUuid()); + assertThat(owners) + .allSatisfy( + owner -> { + assertThat(owner.getId()).isPositive(); + assertThat(owner.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(owner.getAccountUuidSourceNumericId()).isEqualTo(owner.getId()); + }); + assertThat(repository.findByAccountUuids(List.of())).isEmpty(); + } + @Test void rejectedHardDeleteRetainsAccountRowAndSourceIdentityEvidence() { Account saved = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/EntityManagementClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/EntityManagementClientTest.java new file mode 100644 index 0000000000..146632fd5e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/EntityManagementClientTest.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Field; +import java.util.UUID; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +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.entitymanagement.v1.Character; +import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class EntityManagementClientTest { + @Test + void listCharactersByAccountSerializesTheCanonicalAccountUuid() throws Exception { + EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = mockStub(); + Character character = Character.newBuilder().setId("character-1").setName("Mara").build(); + when(stub.listCharactersByAccount(any())) + .thenReturn(ListCharactersByAccountResponse.newBuilder().addCharacters(character).build()); + EntityManagementClient client = newClient(stub); + UUID accountUuid = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + + assertThat( + client.listCharactersByAccount( + 7L, accountUuid, 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .containsExactly(character); + + ArgumentCaptor request = + ArgumentCaptor.forClass(ListCharactersByAccountRequest.class); + verify(stub).listCharactersByAccount(request.capture()); + assertThat(request.getValue().getTenantId()).isEqualTo("7"); + assertThat(request.getValue().getAccountId()).isEqualTo(accountUuid.toString()); + assertThat(request.getValue().getGameInstanceId()).isEqualTo("44"); + assertThat(request.getValue().getPlayableStateScope()) + .isEqualTo(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + } + + @Test + void listCharactersByAccountRejectsNullOrNilUuidBeforeDispatch() throws Exception { + EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = mockStub(); + EntityManagementClient client = newClient(stub); + + assertThrows( + IllegalArgumentException.class, + () -> + client.listCharactersByAccount( + 7L, null, 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + assertThrows( + IllegalArgumentException.class, + () -> + client.listCharactersByAccount( + 7L, new UUID(0L, 0L), 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + verify(stub, never()).listCharactersByAccount(any()); + } + + private static EntityManagementClient newClient( + EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub) throws Exception { + EntityManagementClient client = + new EntityManagementClient( + new ServiceEndpointsProperties(), + new CommonGrpcClientProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop()); + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + return client; + } + + private static EntityManagementServiceGrpc.EntityManagementServiceBlockingStub mockStub() { + return mock(EntityManagementServiceGrpc.EntityManagementServiceBlockingStub.class); + } +} 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 3012f823dd..9d2fdbd2ad 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 @@ -1414,10 +1414,11 @@ private static ListPresenceVisibilityPoliciesRequest presencePolicyRequest( void listPresenceVisibilityPoliciesResolvesAndReturnsCanonicalUuidKeysForSocialPeer() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) - .thenReturn(2L); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(OTHER_ACCOUNT_UUID))) - .thenReturn(3L); + Mockito.when( + accountService.resolveAccountStorageIds( + List.of(UUID.fromString(ACCOUNT_UUID), UUID.fromString(OTHER_ACCOUNT_UUID)))) + .thenReturn( + Map.of(UUID.fromString(ACCOUNT_UUID), 2L, UUID.fromString(OTHER_ACCOUNT_UUID), 3L)); Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L, 3L))) .thenReturn( Map.of( @@ -1454,8 +1455,9 @@ void listPresenceVisibilityPoliciesResolvesAndReturnsCanonicalUuidKeysForSocialP && entry.getPolicy().equals("HIDDEN_STAFF"))); assertTrue(observer.completed()); assertFalse(observer.receivedTransportError()); - Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); - Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(OTHER_ACCOUNT_UUID)); + Mockito.verify(accountService) + .resolveAccountStorageIds( + List.of(UUID.fromString(ACCOUNT_UUID), UUID.fromString(OTHER_ACCOUNT_UUID))); Mockito.verify(accountService).listPresenceVisibilityPolicies(1L, List.of(2L, 3L)); } @@ -1550,12 +1552,13 @@ void listPresenceVisibilityPoliciesOmitsUnknownAndUnprovenSubjects() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); String unprovenAccountUuid = "00000000-0000-4000-8000-000000000003"; - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) - .thenReturn(2L); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(OTHER_ACCOUNT_UUID))) - .thenThrow(new IllegalArgumentException("Account not found")); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(unprovenAccountUuid))) - .thenThrow(new IllegalStateException("Account identity provenance is unavailable")); + Mockito.when( + accountService.resolveAccountStorageIds( + List.of( + UUID.fromString(ACCOUNT_UUID), + UUID.fromString(OTHER_ACCOUNT_UUID), + UUID.fromString(unprovenAccountUuid)))) + .thenReturn(Map.of(UUID.fromString(ACCOUNT_UUID), 2L)); Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) .thenReturn(Map.of(2L, ProfilePresenceVisibilityPolicy.FRIENDS_ONLY)); AccountGrpcService service = @@ -1572,6 +1575,12 @@ void listPresenceVisibilityPoliciesOmitsUnknownAndUnprovenSubjects() { assertEquals(1, observer.response().getPoliciesCount()); assertEquals(ACCOUNT_UUID, observer.response().getPolicies(0).getAccountId()); assertEquals("FRIENDS_ONLY", observer.response().getPolicies(0).getPolicy()); + Mockito.verify(accountService) + .resolveAccountStorageIds( + List.of( + UUID.fromString(ACCOUNT_UUID), + UUID.fromString(OTHER_ACCOUNT_UUID), + UUID.fromString(unprovenAccountUuid))); Mockito.verify(accountService).listPresenceVisibilityPolicies(1L, List.of(2L)); } @@ -1579,10 +1588,11 @@ void listPresenceVisibilityPoliciesOmitsUnknownAndUnprovenSubjects() { void listPresenceVisibilityPoliciesRejectsAliasedResolverRowsWithoutPolicyRead() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) - .thenReturn(2L); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(OTHER_ACCOUNT_UUID))) - .thenReturn(2L); + Mockito.when( + accountService.resolveAccountStorageIds( + List.of(UUID.fromString(ACCOUNT_UUID), UUID.fromString(OTHER_ACCOUNT_UUID)))) + .thenReturn( + Map.of(UUID.fromString(ACCOUNT_UUID), 2L, UUID.fromString(OTHER_ACCOUNT_UUID), 2L)); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); @@ -1603,8 +1613,8 @@ void listPresenceVisibilityPoliciesRejectsAliasedResolverRowsWithoutPolicyRead() void listPresenceVisibilityPoliciesRejectsUnexpectedStorageRowsWithoutPolicyResults() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) - .thenReturn(2L); + Mockito.when(accountService.resolveAccountStorageIds(List.of(UUID.fromString(ACCOUNT_UUID)))) + .thenReturn(Map.of(UUID.fromString(ACCOUNT_UUID), 2L)); Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) .thenReturn(Map.of(3L, ProfilePresenceVisibilityPolicy.PRIVATE)); AccountGrpcService service = @@ -1624,8 +1634,8 @@ void listPresenceVisibilityPoliciesRejectsUnexpectedStorageRowsWithoutPolicyResu void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) - .thenReturn(2L); + Mockito.when(accountService.resolveAccountStorageIds(List.of(UUID.fromString(ACCOUNT_UUID)))) + .thenReturn(Map.of(UUID.fromString(ACCOUNT_UUID), 2L)); Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) .thenThrow(new IllegalArgumentException("Tenant not found")); AccountGrpcService service = @@ -1644,8 +1654,8 @@ void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors assertFalse(notFoundObserver.receivedTransportError()); Mockito.reset(accountService); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) - .thenReturn(2L); + Mockito.when(accountService.resolveAccountStorageIds(List.of(UUID.fromString(ACCOUNT_UUID)))) + .thenReturn(Map.of(UUID.fromString(ACCOUNT_UUID), 2L)); Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) .thenThrow(new IllegalStateException("Policy lookup unavailable")); RecordingObserver internalObserver = 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 5f05920cf4..5a49e68ddc 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 @@ -13,6 +13,7 @@ import ch.qos.logback.core.read.ListAppender; import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; @@ -541,6 +542,63 @@ void rejectsAccountUuidMappingWithoutRecognizedProvenance() { assertThrows(IllegalStateException.class, () -> service.resolveAccountStorageId(accountUuid)); } + @Test + void resolvesPresenceAccountUuidsInOneBatchAndOmitsUnknownOrUnprovenRows() { + UUID validUuid = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + UUID unknownUuid = UUID.fromString("b45dc804-6626-48e4-a657-4a8dfc4e9203"); + UUID unprovenUuid = UUID.fromString("b0c47761-2166-4311-8f2b-327f76f9fd8d"); + Account valid = new Account(); + valid.setId(42L); + valid.setAccountUuid(validUuid); + valid.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + valid.setAccountUuidSourceNumericId(42L); + Account unproven = new Account(); + unproven.setId(43L); + unproven.setAccountUuid(unprovenUuid); + unproven.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_V29_MIGRATION); + unproven.setAccountUuidSourceNumericId(44L); + when(accountRepository.findByAccountUuids(List.of(validUuid, unknownUuid, unprovenUuid))) + .thenReturn(List.of(valid, unproven)); + + assertEquals( + Map.of(validUuid, 42L), + service.resolveAccountStorageIds(List.of(validUuid, unknownUuid, unprovenUuid))); + org.mockito.Mockito.verify(accountRepository) + .findByAccountUuids(List.of(validUuid, unknownUuid, unprovenUuid)); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .findByAccountUuid(org.mockito.ArgumentMatchers.any()); + } + + @Test + void rejectsPresenceAccountUuidBatchWithAliasedPrivateRows() { + UUID firstUuid = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + UUID secondUuid = UUID.fromString("b45dc804-6626-48e4-a657-4a8dfc4e9203"); + Account first = new Account(); + first.setId(42L); + first.setAccountUuid(firstUuid); + first.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + first.setAccountUuidSourceNumericId(42L); + Account second = new Account(); + second.setId(42L); + second.setAccountUuid(secondUuid); + second.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT); + second.setAccountUuidSourceNumericId(42L); + when(accountRepository.findByAccountUuids(List.of(firstUuid, secondUuid))) + .thenReturn(List.of(first, second)); + + assertThrows( + IllegalStateException.class, + () -> service.resolveAccountStorageIds(List.of(firstUuid, secondUuid))); + } + + @Test + void rejectsNilAccountUuidInBatchBeforeRepositoryRead() { + assertThrows( + IllegalArgumentException.class, + () -> service.resolveAccountStorageIds(List.of(new UUID(0L, 0L)))); + verifyNoInteractions(accountRepository); + } + @Test void createAccountPersistsOnlyGlobalIdentity() { CreateAccountRequest request = @@ -3899,7 +3957,7 @@ void listBootstrapCharactersUsesEntityManagementForResolvedRealm() { .setLevel(12) .build(); when(entityManagementClient.listCharactersByAccount( - 7L, 11L, 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + 7L, account.getAccountUuid(), 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(java.util.List.of(character)); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); @@ -3916,6 +3974,9 @@ void listBootstrapCharactersUsesEntityManagementForResolvedRealm() { assertEquals("Mara", characters.getFirst().characterName()); assertEquals("SHARED", characters.getFirst().stateScope()); assertEquals("ALLOW_NEW", characters.getFirst().characterCreationPolicy()); + org.mockito.Mockito.verify(entityManagementClient) + .listCharactersByAccount( + 7L, account.getAccountUuid(), 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @ParameterizedTest @@ -4839,7 +4900,7 @@ void listBootstrapCharactersUsesIsolatedRealmRoster() { .setLevel(4) .build(); when(entityManagementClient.listCharactersByAccount( - 7L, 11L, 91L, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + 7L, account.getAccountUuid(), 91L, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) .thenReturn(java.util.List.of(character)); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); @@ -5032,7 +5093,7 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat .setLevel(9) .build(); when(entityManagementClient.listCharactersByAccount( - 7L, 11L, 91L, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + 7L, account.getAccountUuid(), 91L, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) .thenReturn(java.util.List.of(character)); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); @@ -5109,7 +5170,7 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { admissionPointer( 8L, "demo", "production", "45", 18L, true, true, "SHARED", "ALLOW_NEW")); when(entityManagementClient.listCharactersByAccount( - 7L, 11L, 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + 7L, account.getAccountUuid(), 44L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn(java.util.List.of()); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java index 6f952f4a28..5392ff91b0 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java @@ -30,7 +30,7 @@ public String issueGameplaySessionAttestation( String normalizedRoomInstanceId = requireOptionalCanonicalRuntimeRoomId(roomInstanceId); requireText(tenantId, "tenantId"); requireText(sessionId, "sessionId"); - requireText(accountId, "accountId"); + String canonicalAccountId = requireCanonicalAccountUuid(accountId, "accountId"); requireText(characterId, "characterId"); requireText(gameInstanceId, "gameInstanceId"); requireText(worldSlug, "worldSlug"); @@ -42,7 +42,7 @@ public String issueGameplaySessionAttestation( Map.entry("attestationType", GAMEPLAY_SESSION), Map.entry("tenantId", tenantId), Map.entry("sessionId", sessionId), - Map.entry("accountId", accountId), + Map.entry("accountId", canonicalAccountId), Map.entry("characterId", characterId), Map.entry("gameInstanceId", gameInstanceId), Map.entry("roomInstanceId", normalizedRoomInstanceId), diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java index 3a09bf100d..a13f6a8baa 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java @@ -32,6 +32,40 @@ void requireGameplaySessionMatchAcceptsCanonicalNonNilAccountUuid() { token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); } + @Test + void issueGameplaySessionAttestationRejectsNoncanonicalAccountUuidBeforeSigning() { + JwtUtil signer = org.mockito.Mockito.mock(JwtUtil.class); + GameplaySessionAttestationService issuingService = + new GameplaySessionAttestationService(signer); + + for (String accountId : + new String[] { + "7", + "00000000-0000-0000-0000-000000000000", + ACCOUNT_UUID.toUpperCase(java.util.Locale.ROOT), + " " + ACCOUNT_UUID, + "null", + null + }) { + assertThrows( + GameplaySessionAttestationException.class, + () -> + issuingService.issueGameplaySessionAttestation( + "22", + "41", + accountId, + "123", + "1", + "R-1021", + "demo", + "production", + "17", + "SHARED")); + } + + org.mockito.Mockito.verifyNoInteractions(signer); + } + @Test void requireGameplaySessionMatchRejectsNumericMalformedNoncanonicalAndNilAccountClaims() { assertInvalidAccountIdClaim(7, "Malformed claim: accountId"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java index 4c6f5af9d2..4c22bd135f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java @@ -43,6 +43,35 @@ void listsOnlyThePersistedSharedCharacterForTheRequestedTenantAndAccount() throw } } + @Test + void resetCharactersRestoresDefaultSharedCharactersAfterAnEmptyOverride() throws Exception { + try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { + server.setCharacters(List.of()); + ManagedChannel channel = + ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); + try { + EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = + EntityManagementServiceGrpc.newBlockingStub(channel); + + ListCharactersByAccountResponse emptyResponse = + listCharacters( + stub, "1", accountUuid(7L), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat(emptyResponse.hasError()).isFalse(); + assertThat(emptyResponse.getCharactersList()).isEmpty(); + + server.resetCharacters(); + + ListCharactersByAccountResponse resetResponse = + listCharacters( + stub, "1", accountUuid(7L), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat(resetResponse.hasError()).isFalse(); + assertThat(resetResponse.getCharactersList()).containsExactly(sharedCharacter("Emberline")); + } finally { + channel.shutdownNow(); + } + } + } + @Test void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { Character firstPlayer = From ee5f532deb6a712057b8f002b78f266e5492ab8a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 11:50:12 +1300 Subject: [PATCH 20/34] Clarify UUID retention and log preserved connect context --- .../entity-management-service/api-contracts.md | 2 +- .../entity-management-service/runtime-and-data.md | 2 +- .../implementation-tracking/player-access-and-session.md | 2 +- .../impl/RedisFirstPartyConnectContextRegistry.java | 8 ++++++++ 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 184e73603e..494b25b4e2 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -18,7 +18,7 @@ The standalone, unregistered `EntityPlayerCreatedRosterSourceClient` reads Game The prepared selected-source command and immutable receipt/digest reads remain standalone, unregistered and unqualified. Forward V1011 adds the empty selected source catalogue over the current combined Entity/Saga parent, retaining explicit family and equipment evidence; this does not enable arbitrary authored templates, placement or gameplay admission. Its publication consumption follows the [canonical Game Design profile](../game-design-service/version-control.md#selected-full-publication-profile); current controlled-input proof limits and pending cross-owner qualification belong to the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-entity-and-automation-intake-prerequisite). -Entity V1003–V1010 and the manually composed, unregistered assignment/receipt/roster services are passive source and storage preparation. The canonical roster proto has manually composed certificate-guarded client, peer-interceptor, and read-adapter source definitions, but no automatic runtime handler, client, or service-bean registration. Default component scanning and legacy activation flags leave this family unregistered; [Runtime and Data](./runtime-and-data.md#implementation-status) owns its registration prerequisites. Legacy adapters and consumers retain develop behavior. The qualified immutable donor contains the complete migration tail; focused qualification of this recut, including the default combined Entity/Saga locations and actual-parent upgrade, is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). Neither storage fixtures nor discovery references establish actual owner provenance, fresh Account eligibility, gameplay admission, or PLAY. Authenticated owner handoff and real caller/execution replacement remain required. +Entity V1003–V1010 and the manually composed, unregistered assignment/receipt/roster services are passive source and storage preparation. The canonical roster proto has manually composed certificate-guarded client, peer-interceptor, and read-adapter source definitions, but no automatic runtime handler, client, or service-bean registration. Default component scanning and legacy activation flags leave this family unregistered; [Runtime and Data](./runtime-and-data.md#implementation-status) owns its registration prerequisites. This passive canonical-assignment preparation does not activate its adapters or consumers. Ordinary character reads independently follow the [Account UUID ownership contract](#ordinary-account-ownership); retained rows without a UUID owner are not public character projections. The qualified immutable donor contains the complete migration tail; focused qualification of this recut, including the default combined Entity/Saga locations and actual-parent upgrade, is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). Neither storage fixtures nor discovery references establish actual owner provenance, fresh Account eligibility, gameplay admission, or PLAY. Authenticated owner handoff and real caller/execution replacement remain required. Forward V1016 adds the created snapshot branch to the existing sealed-roster family. Controlled initial owner-to-owner capture, selected read and original-receipt/replay qualification is recorded in the [Entity player-created owner and roster tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation). The test uses actual current owner stores and authenticated transports with coherent controlled historical source; Account, publication and World inputs and test PKI remain controlled. Current guarded post-issuance supersession through recovery/retirement remains unrun. The API, handler and caller remain unregistered; production custody, Account settlement, gameplay admission and activation are unproved. diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 8ce24daa02..f64797775a 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -24,7 +24,7 @@ This document defines Entity Management’s runtime model, persistence ownership - The current `characterGraph` helper caches `getWithInventory(characterId)` by character ID alone with a TTL and performs no namespace or authoritative version validation. It is not the target namespace-qualified Class A `character-cache:*` contract; until that contract is implemented and proved, this cache is not correctness authority. - `EntityDraftDesignDigestServiceImpl` currently emits `digestSchemaVersion=1` without hashing item `equipmentSlotGroupKey`, while `EquipmentServiceImpl` uses that field for slot compatibility admission. The digest is therefore incomplete for equipment semantics: different slot-group constraints may attest the same content digest. Target convergence adds the normalized field, bumps the schema version, and proves cross-version digest isolation plus publish-gate rejection of a changed constraint. -- Entity V1003–V1005 adds independent opaque actor UUIDs, quarantine metadata, exact namespace/scope constraints, and canonical lookup indexes without inferring Account or tenant UUID provenance. Legacy values are retained. The exact canonical repository reader excludes quarantined rows. Existing legacy consumers retain develop behavior for legacy rows, while numeric character, inventory, equipment, friend, resource and condition predicates exclude actors carrying canonical `tenant_uuid` provenance even when their status becomes `QUARANTINED`, including updates and condition expiry. Legitimate legacy/quarantined rows with null canonical tenant provenance retain legacy behavior. Entity's private tenant-row association is not a platform numeric tenant identity; equal numeric values do not authorize legacy access to a canonical actor. Canonical UUID assignment, receipt and roster predicates remain separate. This narrow storage bridge boundary does not activate runtime quarantine enforcement or canonical player admission. +- Entity V1003–V1005 adds independent opaque actor UUIDs, quarantine metadata, exact namespace/scope constraints, and canonical lookup indexes without inferring Account or tenant UUID provenance. Legacy values are retained. The exact canonical repository reader excludes quarantined rows. Ordinary character projections follow the [Account UUID ownership contract](./api-contracts.md#ordinary-account-ownership) and refuse retained rows without UUID ownership. Separately, numeric character, inventory, equipment, friend, resource and condition predicates exclude actors carrying canonical `tenant_uuid` provenance even when their status becomes `QUARANTINED`, including updates and condition expiry. Legitimate legacy/quarantined rows with null canonical tenant provenance retain their existing storage predicates; this does not supply missing Account UUID ownership or authorize a public character projection. Entity's private tenant-row association is not a platform numeric tenant identity; equal numeric values do not authorize legacy access to a canonical actor. Canonical UUID assignment, receipt and roster predicates remain separate. This narrow storage bridge boundary does not activate runtime quarantine enforcement or canonical player admission. - Entity V1006–V1010 adds committed assignment/receipt and sealed roster-snapshot storage with canonical publication identity and exact owner counters. The services and certificate-guarded client/read-adapter source definitions are manually composed and unregistered; neither default scanning nor an optional flag registers them. No authenticated production transport, actor promotion of retained legacy rows, or runtime admission is activated. The detailed assignment/roster contract remains in [Entity API Contracts](./api-contracts.md#implementation-status). - Forward V1016 adds the immutable `PLAYER_CREATED` source identity and created-receipt branch while preserving the `PRESEEDED_ONLY` guards and budgets. The [owning tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation) records qualified controlled initial storage/transport composition and separate retention components. Full guarded post-issuance supersession through retirement remains unrun; the path stays unregistered, with production custody, Account settlement, admission and activation unproved. - Sealed canonical roster snapshots and their actor references are immutable Entity-owned records: append a new snapshot/reference set when the canonical target or roster changes, preserving the existing deletion guards. The [family retention declaration](#sealed-canonical-roster-retention) defines its ADR 0163 obligations. Before any handler, service, or alternative snapshot writer is registered, owner-local disposal must be proved with authoritative terminal/reference/hold carriers and compatible configured horizons. Local carrier and disposal source is prepared with focused qualification; genuine producer composition and registration remain unavailable. See the [implementation tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#canonical-sealed-roster-retention-prerequisite). This does not set a numeric horizon, authorize deletion, or establish indefinite retention. The current passive writer has no registered production call chain; its pending implementation obligation is tracked under #2967 and is not completion or merge proof. 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 c11b77e97a..fab335f46b 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -512,7 +512,7 @@ R1189 passes the complete Account unit task (1,697 passed, zero failures/errors #### Account REST profile UUID selectors -The published B boundary changed legacy `GET /profiles/{accountId}?tenantId=...` and `PUT /profiles/{accountId}` selectors now accept only canonical lowercase non-nil Account UUIDs. PUT's body selector must equal the path selector. The controller resolves the UUID through Account's existing persisted-provenance/source-row resolver, then preserves the current numeric `SessionContext` self-binding and Account service membership check. Reserved presence-policy refusal and post-commit update notification remain in place. This changes only Account REST request identity; ordinary JWT identities, shared forwarding, gRPC `UpdateProfileRequest`, the live Social numeric snapshot selector, and the legacy route/authorization policy remain unchanged and tracked as drift. +At the published B boundary, the legacy `GET /profiles/{accountId}?tenantId=...` and `PUT /profiles/{accountId}` selectors accept only canonical lowercase non-nil Account UUIDs. PUT's body selector must equal the path selector. The controller resolves the UUID through Account's existing persisted-provenance/source-row resolver, then preserves the current numeric `SessionContext` self-binding and Account service membership check. Reserved presence-policy refusal and post-commit update notification remain in place. This changes only Account REST request identity; ordinary JWT identities, shared forwarding, gRPC `UpdateProfileRequest`, the live Social numeric snapshot selector, and the legacy route/authorization policy remain unchanged and tracked as drift. `ProfileControllerTest` adds canonical GET/PUT, numeric/malformed/nil path and body rejection, path/body mismatch, numeric-session wrong-owner refusal, and `AUTH_UNAVAILABLE` mapping for inconsistent or unavailable owner resolution. The native Account application case uses the canonical imported main HTTP configuration and an Account-issued ordinary credential to cover UUID GET/PUT success, selector rejection, mismatch, wrong-owner refusal, missing tenant membership, and reserved-policy refusal while checking the retained numeric profile row. R1202 passes the complete Account unit task (1,701 passed, four existing conditional skips) and all seven native application cases, with zero failures or errors. Enabled main/unit/native analysis, formatting and documentation checks also pass. This is focused local proof; current published-head CI and independent review completion remain separate obligations. The V29 database trigger makes persisted UUID/provenance/source-row fields immutable, so this native fixture cannot corrupt owner evidence; existing Account resolver unit coverage plus the new controller exception cases cover that failure mapping. Existing test transport and workload namespace remain controlled and are not production PKI/namespace proof. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java index dc63ddf28e..1aec2b5c1a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java @@ -7,6 +7,8 @@ import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.data.redis.serializer.SerializationException; @@ -15,6 +17,8 @@ @Service public final class RedisFirstPartyConnectContextRegistry implements FirstPartyConnectContextRegistry { + private static final Logger LOG = + LoggerFactory.getLogger(RedisFirstPartyConnectContextRegistry.class); private static final String KEY_TEMPLATE = "sessionctx:first-party:%d:connect-context"; private final RedisTemplate redisTemplate; @@ -89,6 +93,10 @@ public void unregister(long sessionId) { } catch (SerializationException | ClassCastException | IllegalStateException ex) { // Retain unreadable, incomplete or unverifiable evidence instead of treating it as an absent // context. + LOG.warn( + "Retained first-party connect context kept for session {}: {}", + sessionId, + ex.getClass().getSimpleName()); } } From 84bf96134b43563379b6c9cb33790b36c4cf0466 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 12:23:26 +1300 Subject: [PATCH 21/34] Sanitize UUID owner readback failures and prove HTTP rejection --- .../service/impl/AccountGrpcService.java | 71 ++++++++-- .../service/impl/AccountGrpcServiceTest.java | 126 ++++++++++++++++++ .../ModerationActionControllerTest.java | 40 ++++++ 3 files changed, 227 insertions(+), 10 deletions(-) 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 a99b70b2df..8c6c7df423 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 @@ -61,6 +61,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; import org.springframework.grpc.server.service.GrpcService; import tools.jackson.core.JacksonException; import tools.jackson.databind.JsonNode; @@ -936,8 +937,7 @@ public void exportAccount( try { var data = accountService.exportAccountData( - accountService.resolveAccountStorageId( - requireCanonicalAccountUuid(request.getAccountId()))); + resolveAccountStorageIdForRpc(requireCanonicalAccountUuid(request.getAccountId()))); ExportAccountResponse response = ExportAccountResponse.newBuilder() .setAccountJson(JsonMapper.builder().build().writeValueAsString(data.account())) @@ -945,6 +945,13 @@ public void exportAccount( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AccountUuidReadbackUnavailableException ex) { + ExportAccountResponse response = + ExportAccountResponse.newBuilder() + .setError(accountUuidReadbackUnavailableError("ExportAccount")) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { ExportAccountResponse response = ExportAccountResponse.newBuilder() @@ -977,8 +984,7 @@ public void exportTenantData( var data = accountService.exportTenantData( requirePositiveRequestId(request.getTenantId(), "tenantId"), - accountService.resolveAccountStorageId( - requireCanonicalAccountUuid(request.getAccountId()))); + resolveAccountStorageIdForRpc(requireCanonicalAccountUuid(request.getAccountId()))); ExportTenantDataResponse response = ExportTenantDataResponse.newBuilder() .setTenantId(String.valueOf(data.tenantId())) @@ -990,6 +996,13 @@ public void exportTenantData( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AccountUuidReadbackUnavailableException ex) { + ExportTenantDataResponse response = + ExportTenantDataResponse.newBuilder() + .setError(accountUuidReadbackUnavailableError("ExportTenantData")) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { ExportTenantDataResponse response = ExportTenantDataResponse.newBuilder() @@ -1021,11 +1034,18 @@ public void deleteAccount( try { AdminRoleGuard.requireAdminRole(); accountService.deleteAccount( - accountService.resolveAccountStorageId( - requireCanonicalAccountUuid(request.getAccountId()))); + resolveAccountStorageIdForRpc(requireCanonicalAccountUuid(request.getAccountId()))); DeleteAccountResponse response = DeleteAccountResponse.newBuilder().setSuccess(true).build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AccountUuidReadbackUnavailableException ex) { + DeleteAccountResponse response = + DeleteAccountResponse.newBuilder() + .setSuccess(false) + .setError(accountUuidReadbackUnavailableError("DeleteAccount")) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { DeleteAccountResponse response = DeleteAccountResponse.newBuilder() @@ -1133,8 +1153,7 @@ public void linkExternalAccount( accountService.linkExternalAccount( new net.firedevops.firemud.accountservice.dto.LinkExternalAccountRequest( requirePositiveRequestId(request.getTenantId(), "tenantId"), - accountService.resolveAccountStorageId( - requireCanonicalAccountUuid(request.getAccountId())), + resolveAccountStorageIdForRpc(requireCanonicalAccountUuid(request.getAccountId())), request.getProvider(), request.getExternalId())); var response = @@ -1143,6 +1162,14 @@ public void linkExternalAccount( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AccountUuidReadbackUnavailableException ex) { + var response = + net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() + .setSuccess(false) + .setError(accountUuidReadbackUnavailableError("LinkExternalAccount")) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { var response = net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() @@ -1170,14 +1197,21 @@ public void requestEmailVerification( responseObserver) { try { accountService.requestEmailVerification( - accountService.resolveAccountStorageId( - requireCanonicalAccountUuid(request.getAccountId()))); + resolveAccountStorageIdForRpc(requireCanonicalAccountUuid(request.getAccountId()))); var response = net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() .setSuccess(true) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AccountUuidReadbackUnavailableException ex) { + var response = + net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() + .setSuccess(false) + .setError(accountUuidReadbackUnavailableError("RequestEmailVerification")) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { var response = net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() @@ -1238,6 +1272,23 @@ private net.firedevops.firemud.shared.v1.ErrorDetail sourceEvidenceUnavailableEr return appError(operation, "AUTH_UNAVAILABLE", "Account authority is unavailable"); } + private net.firedevops.firemud.shared.v1.ErrorDetail accountUuidReadbackUnavailableError( + String operation) { + return appError(operation, "AUTH_UNAVAILABLE", AUTHORITY_UNAVAILABLE_MESSAGE); + } + + private long resolveAccountStorageIdForRpc(UUID accountUuid) { + try { + return accountService.resolveAccountStorageId(accountUuid); + } catch (IllegalStateException | DataAccessException ex) { + throw new AccountUuidReadbackUnavailableException(); + } + } + + private static final class AccountUuidReadbackUnavailableException extends RuntimeException { + private static final long serialVersionUID = 1L; + } + private net.firedevops.firemud.shared.v1.ErrorDetail appError( String operation, String code, String message) { return meterRegistry == null 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 9d2fdbd2ad..8d888ae8b5 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 @@ -15,6 +15,7 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Stream; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.AuthenticateResponse; @@ -61,10 +62,12 @@ import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.AfterEach; 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.Mockito; import org.springframework.dao.DataAccessResourceFailureException; @@ -72,6 +75,8 @@ class AccountGrpcServiceTest { private static final String WORKLOAD_NAMESPACE = "test"; private static final String ACCOUNT_UUID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + private static final String ACCOUNT_UUID_READBACK_FAILURE = + "internal Account UUID source evidence mismatch"; private static final String OTHER_ACCOUNT_UUID = "a2e1342e-a139-49c6-a460-c8e25f6697ae"; private static final String REALM_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; private static final String OTHER_REALM_ID = "57c58f36-c5ea-4aa8-8ef7-91a45e407f01"; @@ -146,6 +151,30 @@ void tearDown() { SessionContext.clear(); } + private static Stream accountUuidReadbackFailures() { + return Stream.of( + new IllegalStateException(ACCOUNT_UUID_READBACK_FAILURE), + new DataAccessResourceFailureException(ACCOUNT_UUID_READBACK_FAILURE)); + } + + private static AccountService accountServiceWithUnavailableAccountUuidReadback( + RuntimeException failure) { + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenThrow(failure); + return accountService; + } + + private static void assertAccountUuidReadbackUnavailable( + RecordingObserver observer, ErrorDetail error) { + assertEquals(1, observer.nextCalls); + assertFalse(observer.receivedTransportError()); + assertEquals(1, observer.completedCalls); + assertEquals("AUTH_UNAVAILABLE", error.getCode()); + assertEquals("Account authority unavailable; retry later", error.getMessage()); + assertFalse(error.getMessage().contains(ACCOUNT_UUID_READBACK_FAILURE)); + } + @Test void pingReturnsPong() { PingService pingService = Mockito.mock(PingService.class); @@ -2621,6 +2650,103 @@ public void onCompleted() {} Mockito.verifyNoInteractions(accountService); } + @ParameterizedTest + @MethodSource("accountUuidReadbackFailures") + void exportAccountSanitizesUnavailableAccountUuidReadback(RuntimeException failure) { + AccountService accountService = accountServiceWithUnavailableAccountUuidReadback(failure); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), accountService); + RecordingObserver observer = new RecordingObserver<>(); + + service.exportAccount( + ExportAccountRequest.newBuilder().setAccountId(ACCOUNT_UUID).build(), observer); + + assertAccountUuidReadbackUnavailable(observer, observer.response().getError()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService, Mockito.never()).exportAccountData(Mockito.anyLong()); + } + + @ParameterizedTest + @MethodSource("accountUuidReadbackFailures") + void exportTenantDataSanitizesUnavailableAccountUuidReadback(RuntimeException failure) { + AccountService accountService = accountServiceWithUnavailableAccountUuidReadback(failure); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), accountService); + RecordingObserver observer = new RecordingObserver<>(); + + service.exportTenantData( + ExportTenantDataRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), + observer); + + assertAccountUuidReadbackUnavailable(observer, observer.response().getError()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService, Mockito.never()) + .exportTenantData(Mockito.anyLong(), Mockito.anyLong()); + } + + @ParameterizedTest + @MethodSource("accountUuidReadbackFailures") + void deleteAccountSanitizesUnavailableAccountUuidReadback(RuntimeException failure) { + AccountService accountService = accountServiceWithUnavailableAccountUuidReadback(failure); + SessionContext.setContext(OTHER_ACCOUNT_UUID, List.of("platformAdmin"), Map.of()); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), accountService); + RecordingObserver observer = new RecordingObserver<>(); + + service.deleteAccount( + DeleteAccountRequest.newBuilder().setAccountId(ACCOUNT_UUID).build(), observer); + + assertFalse(observer.response().getSuccess()); + assertAccountUuidReadbackUnavailable(observer, observer.response().getError()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService, Mockito.never()).deleteAccount(Mockito.anyLong()); + } + + @ParameterizedTest + @MethodSource("accountUuidReadbackFailures") + void linkExternalAccountSanitizesUnavailableAccountUuidReadback(RuntimeException failure) { + AccountService accountService = accountServiceWithUnavailableAccountUuidReadback(failure); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), accountService); + RecordingObserver observer = + new RecordingObserver<>(); + + service.linkExternalAccount( + net.firedevops.firemud.account.v1.LinkExternalAccountRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .setProvider("google") + .setExternalId("external-1") + .build(), + observer); + + assertFalse(observer.response().getSuccess()); + assertAccountUuidReadbackUnavailable(observer, observer.response().getError()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService, Mockito.never()).linkExternalAccount(Mockito.any()); + } + + @ParameterizedTest + @MethodSource("accountUuidReadbackFailures") + void requestEmailVerificationSanitizesUnavailableAccountUuidReadback(RuntimeException failure) { + AccountService accountService = accountServiceWithUnavailableAccountUuidReadback(failure); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), accountService); + RecordingObserver observer = + new RecordingObserver<>(); + + service.requestEmailVerification( + net.firedevops.firemud.account.v1.RequestEmailVerificationRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .build(), + observer); + + assertFalse(observer.response().getSuccess()); + assertAccountUuidReadbackUnavailable(observer, observer.response().getError()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService, Mockito.never()).requestEmailVerification(Mockito.anyLong()); + } + @Test void deleteAccountRequiresAdminRole() { PingService pingService = Mockito.mock(PingService.class); diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java index 031b044e69..f2ee3445cc 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/ModerationActionControllerTest.java @@ -5,6 +5,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import java.util.HashMap; import java.util.List; import java.util.Map; import net.firedevops.firemud.common.GlobalExceptionHandler; @@ -113,4 +114,43 @@ void applyRejectsZeroSessionIdBeforeDispatch() throws Exception { verifyNoInteractions(service); } + + @Test + void applyRejectsInvalidAccountUuidDuringJsonDeserialization() throws Exception { + String token = + jwtUtil.generateToken( + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); + Map request = + new HashMap<>( + Map.of( + "tenantId", + 1L, + "accountId", + ACCOUNT_ID, + "sessionId", + 9L, + "action", + "ban", + "reason", + "")); + Object[] invalidAccountIds = { + 123L, "not-a-uuid", "00000000-0000-0000-0000-000000000000", ACCOUNT_ID.toUpperCase(), null + }; + + for (Object invalidAccountId : invalidAccountIds) { + request.put("accountId", invalidAccountId); + mockMvc + .perform( + post("/moderation/actions") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request)) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.status").value("ERROR")) + .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) + .andExpect(jsonPath("$.error.message").value("Request body is malformed")); + } + + verifyNoInteractions(service); + } } From 400df84f28f82f2b198c7ae13fa84398b369c16d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 13:15:26 +1300 Subject: [PATCH 22/34] Wire batched UUID ownership into presence auth fixture --- .../security/AccountRuntimeConsumerAuthWiringTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountRuntimeConsumerAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountRuntimeConsumerAuthWiringTest.java index 7807772628..60b289c3f2 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountRuntimeConsumerAuthWiringTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountRuntimeConsumerAuthWiringTest.java @@ -122,8 +122,8 @@ void exactSocialPeerReachesPresencePolicyHandlerWithoutBearerUnderBothYamlLayers productionLayer, (interceptor, ignored) -> { AccountService accountService = mock(AccountService.class); - when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) - .thenReturn(42L); + when(accountService.resolveAccountStorageIds(List.of(UUID.fromString(ACCOUNT_UUID)))) + .thenReturn(Map.of(UUID.fromString(ACCOUNT_UUID), 42L)); when(accountService.listPresenceVisibilityPolicies(1L, List.of(42L))) .thenReturn(Map.of(42L, ProfilePresenceVisibilityPolicy.PRIVATE)); AccountGrpcService service = @@ -138,7 +138,7 @@ void exactSocialPeerReachesPresencePolicyHandlerWithoutBearerUnderBothYamlLayers assertThat(result.observer().response.getPolicies(0).getAccountId()) .isEqualTo(ACCOUNT_UUID); assertThat(result.observer().response.getPolicies(0).getPolicy()).isEqualTo("PRIVATE"); - verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + verify(accountService).resolveAccountStorageIds(List.of(UUID.fromString(ACCOUNT_UUID))); verify(accountService).listPresenceVisibilityPolicies(1L, List.of(42L)); }); } From 5b7d8b95be8c72c3db13a762b3fbcbf9fb08d69d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 13:49:33 +1300 Subject: [PATCH 23/34] Prove retained owner refusal and remove obsolete seeder dependency --- .../account-service/api-contracts.md | 2 +- .../impl/CharacterServiceImplTest.java | 41 +++++++++++++++++++ .../loggingadmin/data/TestDataSeeder.java | 2 - .../loggingadmin/data/TestDataSeederTest.java | 8 +--- 4 files changed, 43 insertions(+), 10 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 34adf67b1c..a9246031c5 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -118,7 +118,7 @@ The unregistered canonical `Authenticate` receiver requires the exact same-names `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. -In the ordinary Account gRPC methods, Account-valued selectors and authentication/bootstrap results use canonical Account UUID text, including `Authenticate`, `IssuePlayerBootstrapToken`, `GetProfile`, and `UpdateProfile`. For these operations Account resolves UUID selectors to numeric rows only for local storage access; the row is not exposed as the Account identity. Separate internal identity-provenance reads retain their own contract. `InternalRuntimeController`'s privileged numeric realm-grant management DTOs remain a separate unconverted boundary; see the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-account-uuid-receiving-preparation). +Ordinary Account gRPC methods use canonical Account UUID text for Account-valued selectors and authentication results, including `Authenticate`, `GetProfile`, and `UpdateProfile`. The local `IssuePlayerBootstrapToken` application operation behind REST `POST /auth/player-bootstrap` returns the same canonical UUID identity; it is not a gRPC method. Account resolves UUID selectors to numeric rows only for local storage access; the row is not exposed as the Account identity. Separate internal identity-provenance reads retain their own contract. `InternalRuntimeController`'s privileged numeric realm-grant management DTOs remain a separate unconverted boundary; see the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-account-uuid-receiving-preparation). - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `account_service.proto`. - `CreateAccount` – registers a global Account identity and returns its canonical UUID as REST `AccountDto.id` and gRPC `CreateAccountResponse.account_id`; its platform audit outbox payload carries the same UUID. It does not select a tenant or create membership/profile state. diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java index c1a8bd9b14..a611ba654a 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java @@ -1,7 +1,11 @@ package net.firedevops.firemud.entitymanagement.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; @@ -20,6 +24,43 @@ class CharacterServiceImplTest { + @Test + void retainedUnresolvedOwnerCannotBeProjectedOrCached() { + CharacterRepository repo = Mockito.mock(CharacterRepository.class); + var cacheManager = new ConcurrentMapCacheManager("characterGraph"); + CharacterServiceImpl service = + new CharacterServiceImpl( + repo, + Mappers.getMapper(CharacterMapper.class), + cacheManager, + new SimpleMeterRegistry(), + new PlayableStateKeyResolver(), + new ScopedCharacterResolver(repo, new PlayableStateKeyResolver())); + service.initMetrics(); + Character retained = new Character(); + retained.setId(1L); + retained.setTenantId(1L); + retained.setAccountId(42L); + retained.setAccountUuid(null); + retained.setPlayableStateKey("shared-live"); + retained.setName("Retained"); + when(repo.findWithInventoryById(1L)).thenReturn(Optional.of(retained)); + when(repo.findByTenantIdAndPlayableStateKeyAndNameIgnoreCase(1L, "shared-live", "Retained")) + .thenReturn(Optional.of(retained)); + + assertThrows(IllegalArgumentException.class, () -> service.getWithInventory(1L)); + assertThrows( + IllegalArgumentException.class, + () -> + service.findByGameplayScopeAndName( + 1L, "live", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "Retained")); + + assertNull(cacheManager.getCache("characterGraph").get(1L)); + assertEquals(42L, retained.getAccountId()); + assertNull(retained.getAccountUuid()); + verify(repo, never()).save(any()); + } + @Test void gainExperienceLevelsUp() { CharacterRepository repo = Mockito.mock(CharacterRepository.class); diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/data/TestDataSeeder.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/data/TestDataSeeder.java index 56bddcc0c8..7c2f863e66 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/data/TestDataSeeder.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/data/TestDataSeeder.java @@ -6,7 +6,6 @@ import net.firedevops.firemud.loggingadmin.entity.LogEvent; import net.firedevops.firemud.loggingadmin.entity.PlayerReport; import net.firedevops.firemud.loggingadmin.repository.LogEventRepository; -import net.firedevops.firemud.loggingadmin.repository.ModerationActionRepository; import net.firedevops.firemud.loggingadmin.repository.PlayerReportRepository; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; @@ -31,7 +30,6 @@ public class TestDataSeeder implements ApplicationRunner { private final LogEventRepository logEventRepository; private final PlayerReportRepository playerReportRepository; - private final ModerationActionRepository moderationActionRepository; @Override @Transactional diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/data/TestDataSeederTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/data/TestDataSeederTest.java index 76824c5e8f..6f816ce3ef 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/data/TestDataSeederTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/data/TestDataSeederTest.java @@ -7,7 +7,6 @@ import java.util.Optional; import net.firedevops.firemud.loggingadmin.repository.LogEventRepository; -import net.firedevops.firemud.loggingadmin.repository.ModerationActionRepository; import net.firedevops.firemud.loggingadmin.repository.PlayerReportRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,15 +17,13 @@ class TestDataSeederTest { @Mock LogEventRepository logEventRepository; @Mock PlayerReportRepository playerReportRepository; - @Mock ModerationActionRepository moderationActionRepository; private TestDataSeeder seeder; @BeforeEach void setup() { MockitoAnnotations.openMocks(this); - seeder = - new TestDataSeeder(logEventRepository, playerReportRepository, moderationActionRepository); + seeder = new TestDataSeeder(logEventRepository, playerReportRepository); } @Test @@ -41,7 +38,6 @@ void runSeedsCanonicalRowsWhenMissing() throws Exception { verify(logEventRepository).save(any()); verify(playerReportRepository).save(any()); - org.mockito.Mockito.verifyNoInteractions(moderationActionRepository); } @Test @@ -56,9 +52,7 @@ void runReassertsCanonicalRowsWhenTheyAlreadyExist() throws Exception { verify(logEventRepository).save(any()); verify(playerReportRepository).save(any()); - org.mockito.Mockito.verifyNoInteractions(moderationActionRepository); verify(logEventRepository, never()).count(); verify(playerReportRepository, never()).count(); - verify(moderationActionRepository, never()).count(); } } From a692d13ddea9c6dffd33ee91de822a8f5f667e51 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 13:52:37 +1300 Subject: [PATCH 24/34] Use explicit Account UUID lookup throughout final Entity callers --- .../service/impl/CharacterServiceImpl.java | 2 +- .../PreseededActorAssignmentIntegrationTest.java | 4 ++-- .../RetainedActorIdentityIntegrationTest.java | 2 +- .../service/impl/CharacterServiceImplListTest.java | 8 ++++---- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java index adcfb9ed65..14d2896cea 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java @@ -143,7 +143,7 @@ public Page listForGameplayScope( Pageable pageable) { requireAccountOwner(accountId); return characterRepository - .findByTenantIdAndAccountIdAndPlayableStateKey( + .findByTenantIdAndAccountUuidAndPlayableStateKey( tenantId, accountId, playableStateKeyResolver.resolve(gameInstanceId, playableStateScope), diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java index b2d977b915..4bdb401b53 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -1067,7 +1067,7 @@ private void assertNumericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAn canonicalCharacterId, entityTenantRowId, namespaceUuid.toString())) .isEmpty(); assertThat( - characterRepository.findByTenantIdAndAccountIdAndPlayableStateKey( + characterRepository.findByTenantIdAndAccountUuidAndPlayableStateKey( entityTenantRowId, accountUuid, namespaceUuid.toString(), Pageable.unpaged())) .isEmpty(); assertThat( @@ -1097,7 +1097,7 @@ private void assertNumericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAn assertThat(characterRepository.findByIdAndTenantId(legacyCharacterId, entityTenantRowId)) .isPresent(); assertThat( - characterRepository.findByTenantIdAndAccountIdAndPlayableStateKey( + characterRepository.findByTenantIdAndAccountUuidAndPlayableStateKey( entityTenantRowId, accountUuid, "shared-live", Pageable.unpaged())) .isEmpty(); assertThat(legacy.getAccountUuid()).isNull(); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index 7ce62e1002..8a99c99f21 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -127,7 +127,7 @@ void legacySaveAllocatesQuarantinedUuidAndPreservesLegacyReadbackAndUpdates() { .isPresent(); assertThat( characterRepository - .findByTenantIdAndAccountIdAndPlayableStateKey( + .findByTenantIdAndAccountUuidAndPlayableStateKey( tenantId, accountUuid, actor.getPlayableStateKey(), null) .getContent()) .isEmpty(); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java index 9631ad6265..2ebc175479 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java @@ -47,7 +47,7 @@ void listForTenantAndAccountReturnsDtos() { c.setPlayableStateKey("shared-live"); c.setName("Hero"); - when(repo.findByTenantIdAndAccountIdAndPlayableStateKey( + when(repo.findByTenantIdAndAccountUuidAndPlayableStateKey( 1L, OWNER, "shared-live", Pageable.unpaged())) .thenReturn(new PageImpl<>(List.of(c))); @@ -58,7 +58,7 @@ void listForTenantAndAccountReturnsDtos() { assertEquals("Hero", result.getContent().get(0).name()); assertEquals(OWNER, result.getContent().get(0).accountId()); verify(repo) - .findByTenantIdAndAccountIdAndPlayableStateKey( + .findByTenantIdAndAccountUuidAndPlayableStateKey( 1L, OWNER, "shared-live", Pageable.unpaged()); } @@ -78,7 +78,7 @@ void listForTenantAndAccountDoesNotCrossTenantBoundary() { new ScopedCharacterResolver(repo, new PlayableStateKeyResolver())); service.initMetrics(); - when(repo.findByTenantIdAndAccountIdAndPlayableStateKey( + when(repo.findByTenantIdAndAccountUuidAndPlayableStateKey( 2L, OWNER, "instance:91", Pageable.unpaged())) .thenReturn(new PageImpl<>(List.of())); @@ -87,7 +87,7 @@ void listForTenantAndAccountDoesNotCrossTenantBoundary() { 2L, OWNER, "91", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, Pageable.unpaged()); assertEquals(0, result.getTotalElements()); verify(repo) - .findByTenantIdAndAccountIdAndPlayableStateKey( + .findByTenantIdAndAccountUuidAndPlayableStateKey( 2L, OWNER, "instance:91", Pageable.unpaged()); } } From b6fea69d910fbb94ebc9469586f974fa709f892d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:15:48 +1300 Subject: [PATCH 25/34] Preserve safe Account outage handling and qualify UUID correlation guards --- .../account-service/api-contracts.md | 2 +- .../api-contracts.md | 2 +- design/grpc-docs/grpc-api.md | 2 +- .../player-access-and-session.md | 4 +- .../v1/entity_management_service.proto | 2 +- .../repository/AccountRepository.java | 7 ++- .../service/impl/AccountGrpcService.java | 11 +++- .../AccountRuntimeConsumerAuthWiringTest.java | 21 ++++++-- .../service/impl/AccountGrpcServiceTest.java | 53 ++++++++++++++++++- .../impl/ModerationServiceImplTest.java | 7 ++- 10 files changed, 95 insertions(+), 16 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index a9246031c5..8213ecd7ac 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -132,7 +132,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `IssueAutomationOperatorAuthorizationReference` – target Account-owned typed issuance RPC for the exact Logging & Admin workload mTLS identity and a versioned automation policy. It is a separate automation-specific tenant-scoped authority path, not a human membership or `control-ui` path; until a published schema registry exists, its target-not-routable contract explicitly selects only the `non_moderation` branch, requires schema-declared `action_category` absence, and rejects moderation schemas before issuance. Account validates the `automation_operator` issuance kind, exact authenticated workload binding, policy identity/version, `tenant_generation`, target/scope, action-family schema pair, typed request fields, `controlPlaneRequestId`, canonical `mutationDigest`, `reservationOwnerId`, and positive `reservationClaimFence`, and issues no user or global-role authority. `controlPlaneRequestId` and `mutationDigest/v1` are the mutation identity and digest only for that non-moderation branch; a future moderation automation path must use dedicated moderation identities, digests, and idempotency and must treat `controlPlaneRequestId` as correlation-only. - `RedeemOperatorAuthorization` – target Account-owned redemption RPC used only by the exact owner workload named in the issued record. The owner presents the exact opaque reference plus the Account-returned `authorizationReferenceFingerprint` transported unchanged through Logging & Admin, its independently derived action family, schema pair, typed target/scope/request fields, `controlPlaneRequestId`, canonical `mutationDigest`, `reservationOwnerId`, and positive `reservationClaimFence`; Account authenticates the exact mTLS caller and returns the authenticated authority projection, a fresh Account recomputation of `authorizationReferenceFingerprint`, and immutable `authorityEvidenceBundle` only when every value and current authority state still match. The owner compares the forwarded fingerprint with that fresh Account value before treating redemption as successful or authorizing the mutation. Account consumes the reference atomically on successful redemption and durably records the redemption result. Before successful redemption, an exact same-tuple retry may replay that durable result; after consumption, any replayed result is evidence for the same completed redemption only and cannot authorize a new owner attempt. Owner rearm after a terminal result requires fresh Account authorization and a new opaque reference. - `RecoverOperatorAuthorizationReference` – target Account-owned read-only recovery RPC for the exact authenticated Logging & Admin workload. The request repeats the complete immutable typed issuance tuple, actor or automation-policy evidence, and current reservation owner/claim fence; Account returns only the original issuance response or original terminal outcome from its durable record. Durable `NOT_FOUND` is read-only lookup evidence that no matching record was found, never proof for `NOT_EXECUTED_BEFORE_AUTHORIZATION`; that terminal state requires durable phase evidence that Account authorization cannot complete and durable dispatch evidence that no owner-forward call occurred and no owner-forward call can still occur. Until both proofs exist, the operation remains `AUTHORIZATION_PENDING`, non-replayable and non-rearmable. It never issues, extends, rotates, redeems, or semantically recreates a reference. -- Account-owned response identity follows [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity); gRPC request selectors retain their current contracts. +- Account-owned response identity follows [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity); the ordinary gRPC methods listed above use canonical Account UUID selectors. Privileged numeric realm-grant DTOs remain a separate unconverted boundary. - `GetProfile` – retrieves the caller's profile relationship through canonical `GET /tenants/{tenantId}/profiles/{accountId}`, classified `tenant_regular`. Caller subject, scoped-role, and membership-generation validation follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. - `UpdateProfile` – modifies the caller's profile relationship through canonical `PUT /tenants/{tenantId}/profiles/{accountId}` under the same `tenant_regular` authorization and caller-subject binding. Membership authority follows [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the local API triggers notification emails. The response projection returns `PRIVATE` for a retained legacy `HIDDEN_STAFF` value without rewriting the stored row; normative policy remains in [ADR 0046](../../decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). The legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 494b25b4e2..0db89021b6 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -24,7 +24,7 @@ Forward V1016 adds the created snapshot branch to the existing sealed-roster fam The manually composed Account/Game Session evidence bridge currently supports `SHARED` only; the assignment bridge requires already canonical, non-nil UUID game-instance text under the existing bridge contract. Those bounded adapters supply no owner proof outside their declared scope. They do not narrow the passive assignment core, which supports `SHARED` and `ISOLATED` and hashes exact bounded opaque game-instance text without parsing or normalization. -The target read semantics are: any policy other than `PRESEEDED_ONLY` is non-authorizing and returns `FAILED_PRECONDITION`; `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. PRESEEDED_ONLY actor display names are nonblank, trimmed, control-free text bounded to 100 Unicode code points, matching the accepted assignment core. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. It also returns the original non-nil assignment operation UUID and immutable intent digest from the unique matching committed `ASSIGNED` `PRESEEDED_ONLY` `PLAYER` receipt. Entity resolves that receipt only for the exact account, selected actor, complete expected target, current owner counters, and published owner-proof digest; zero or multiple matches disclose no reference, and readback must match the same receipt. The response is persisted owner evidence, not a newly minted identity, an admission grant, or proof that Account eligibility remains current. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. +The target read semantics are: any policy other than `PRESEEDED_ONLY` is non-authorizing and returns `FAILED_PRECONDITION`; `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. PRESEEDED_ONLY actor display names are nonblank, trimmed, control-free text bounded to 100 Unicode code points, matching the accepted assignment core. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. It also returns the original non-nil assignment operation UUID and immutable intent digest from the unique matching committed `ASSIGNED` `PRESEEDED_ONLY` `PLAYER` receipt. Entity resolves that receipt only for the exact account, selected actor, complete expected target, current owner counters, and published owner-proof digest; zero or multiple matches disclose no reference, and readback must match the same receipt. The response is persisted owner evidence, not a newly minted identity, an admission grant, or proof that Account eligibility remains current. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the ordinary UUID-valued `ListCharactersByAccount` RPC for canonical gameplay. Before its owner RPC, Entity reserves an owner-local admission nonce for the exact original request. Entity independently reads the exact original Game Session selection through [its authenticated owner-reference contract](../game-session-service/api-contracts.md#original-canonical-roster-selection-reference). Capture commits the sealed snapshot, immutable original-operation/Game Session target-fence receipt and `ORIGINAL_SELECTION` retention reference in one Entity transaction, conditionally matching that same still-open local admission nonce. A failed bind rolls the new snapshot and reference back. A retry of that original operation returns its immutable local receipt rather than silently binding a later roster. The selected-assignment read names the same original request UUID and recorded snapshot; a fresh request UUID is a different operation. Disposal revokes the local nonce in the same transaction; an older delayed handler cannot recreate a disposed snapshot after payload or tombstone cleanup. This source boundary remains unregistered. Only complete authenticated Game Session target-retirement evidence, local reference/hold closure, exact local epochs and Entity-owned horizons can qualify the owner-local disposal path described in [Runtime and Data](./runtime-and-data.md#sealed-canonical-roster-retention). Entity shares acquisition closure across sibling snapshots for the same account and full target while retaining each snapshot's proof and disposal qualification independently. Its non-authoritative `entity_canonical_roster_snapshot_targets` inventory identifies exact-target siblings even when direct capture left no admission/original row; it grants no retirement, disposal or release authority, and unresolved source classification keeps the boundary protected. Existing sibling records remain readable after the first retirement seal, but that does not authorize delayed capture. diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index 668096ab03..7f13582658 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -8675,7 +8675,7 @@ Canonical gameplay roster discovery is a pre-admission, non-admitting boundary. preseeded methods below remain restricted to PRESEEDED_ONLY; other policy values are non-authorizing and fail with FAILED_PRECONDITION. The PLAYER_CREATED methods are a separate source-bound read contract and do not authenticate their unsigned context or authorize the -legacy numeric ListCharactersByAccount RPC for canonical gameplay. A valid ListPreseededRoster +ordinary UUID-valued ListCharactersByAccount RPC for canonical gameplay. A valid ListPreseededRoster response may contain zero actors; that is a successful lookup. These RPCs use canonical non-OK gRPC statuses rather than in-response errors: malformed requests are INVALID_ARGUMENT, stale snapshots or selections not present in the bound snapshot are FAILED_PRECONDITION, unauthorized callers are 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 fab335f46b..9aae49e2d2 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -484,13 +484,13 @@ Live Account authentication hashes and verifies passwords with `argon2-jvm` Argo The authentication owner-preparation component enforces the existing Account UUID/provenance/source-row owner at ordinary control-UI authentication, gameplay password authentication, verified-email OTP completion, and player-bootstrap issuance. After successful credential and lifecycle checks, issuance requires the existing UUID lookup to resolve back to the authenticated row before challenge consumption, signing, or session mutation. Missing, nil, inconsistent, or unavailable identity evidence returns `AUTH_UNAVAILABLE`; invalid-credential behavior remains separate. That component adds no Account UUID storage, mapping subsystem, schema, wire/profile transition, or downstream activation. The qualified owner-preparation checkpoint retained numeric authentication/bootstrap results and JWT Account claims; the published bootstrap-only credential and scope transitions are recorded below, followed by the current unpublished ordinary UUID receiving preparation. -Focused R1130 passes all 269 selected executions: 211 `AccountServiceImplTest` cases, 52 `AccountGrpcServiceTest` cases and six native application cases, with zero failures, errors or skips. `AccountServiceImplTest` covers the four issuance entry points against missing/nil UUID, missing provenance/source row, inconsistent source row, missing UUID lookup, different returned owner/UUID, and unavailable readback, with no signing, successful-challenge deletion, or session write on refusal. Positive and invalid-credential cases retain their current contracts; existing issuance fixtures explicitly supply test-owned persisted UUID associations. `AccountGrpcServiceTest` covers `AUTH_UNAVAILABLE` propagation for password and email-OTP receivers. `AccountApplicationIntegrationTest.ordinaryAuthenticationAndBootstrapPreservePersistedOwnerAndCurrentNumericContract` passes physical PostgreSQL/Redis registration-to-login/bootstrap proof with unchanged UUID provenance/source rows and numeric ordinary response/JWT assertions. Affected compilation, enabled Account main/test/integration static analysis, formatting and documentation checks pass. Consolidated receiving R1137 also runs the complete Account unit task: 1679 reported cases with zero failures/errors and four existing conditional trust-permission cases skipped, plus all six selected native application cases. Enabled affected main/test/integration analysis, formatting and documentation checks pass. These are historical owner-preparation results; later UUID receiving qualification and its runtime limits are recorded under [Ordinary UUID issuer and receiving](#ordinary-uuid-issuer-and-receiving). +Focused R1130 passes all 269 selected executions: 211 `AccountServiceImplTest` cases, 52 `AccountGrpcServiceTest` cases and six native application cases, with zero failures, errors or skips. `AccountServiceImplTest` covers the four issuance entry points against missing/nil UUID, missing provenance/source row, inconsistent source row, missing UUID lookup, different returned owner/UUID, and unavailable readback, with no signing, successful-challenge deletion, or session write on refusal. Positive and invalid-credential cases retain their current contracts; existing issuance fixtures explicitly supply test-owned persisted UUID associations. `AccountGrpcServiceTest` covers `AUTH_UNAVAILABLE` propagation for password and email-OTP receivers. `AccountApplicationIntegrationTest.ordinaryAuthenticationAndBootstrapPreservePersistedOwnerAndCurrentNumericContract` (historical owner-preparation name; the current combined UUID journey is `ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity`) passes physical PostgreSQL/Redis registration-to-login/bootstrap proof with unchanged UUID provenance/source rows and numeric ordinary response/JWT assertions. Affected compilation, enabled Account main/test/integration static analysis, formatting and documentation checks pass. Consolidated receiving R1137 also runs the complete Account unit task: 1679 reported cases with zero failures/errors and four existing conditional trust-permission cases skipped, plus all six selected native application cases. Enabled affected main/test/integration analysis, formatting and documentation checks pass. These are historical owner-preparation results; later UUID receiving qualification and its runtime limits are recorded under [Ordinary UUID issuer and receiving](#ordinary-uuid-issuer-and-receiving). #### Player-bootstrap UUID credential profile The published #3352 credential boundary migrates only `PlayerBootstrapResult.accountId` and the `player-bootstrap` JWT subject/Account claim to the persisted Account UUID. Successful password and email-OTP issuance retains the existing owner validation before challenge consumption, signing and session storage. The dedicated Account reader accepts only canonical non-nil UUID subject/claim equality, resolves the existing owner row before session access, and has no numeric compatibility path. Malformed/mismatched identity is `CONNECT_CONTEXT_INVALID`; unavailable/inconsistent owner readback is `AUTH_UNAVAILABLE`; inactive Account-local sessions remain invalid context. Numeric Account-local session and membership row keys remain private implementation details. -R1140 passes the complete Account unit task: 1697 reported cases, zero failures/errors and four existing conditional trust-permission skips. Its selected native aggregate initially failed the new email-verification journey because the test omitted the verification URL; enabled integration analysis also found three nullable fixture reads. R1145 passes all six selected native application cases, zero failures/errors/skips, after explicit test-owned mail configuration and required-record/recipient handling. Enabled affected main/test/integration analysis, formatting and documentation checks pass. `AccountApplicationIntegrationTest.bootstrapUsesPersistedUuidAcrossPasswordOtpReadsAndInvalidationWhileOrdinaryLoginStaysNumeric` executes real registration, unchanged numeric ordinary login, password bootstrap, actual email verification and generated-email-OTP bootstrap, UUID JWT/result assertions, subsequent HTTP bootstrap reads, successful-challenge removal and physical Redis session invalidation with unchanged persisted Account UUID/provenance/source-row identity. Its external Game Session discovery response and mail delivery remain controlled fixtures. Receiving R1147 at `89adf8951db3` on the qualified owner-diagnostic parent `584c336b55d0` passes all 229 Account service cases and the actual registration/password/OTP/bootstrap/session-invalidation native case, with zero failures/errors/skips and enabled affected analysis, formatting and documentation checks. Later parent carries retain the verified retention test and observation entries; their source attribution remains separate from this bootstrap proof. This is focused local proof; unfiltered native service execution and published-source CI/review remain separate obligations. +R1140 passes the complete Account unit task: 1697 reported cases, zero failures/errors and four existing conditional trust-permission skips. Its selected native aggregate initially failed the new email-verification journey because the test omitted the verification URL; enabled integration analysis also found three nullable fixture reads. R1145 passes all six selected native application cases, zero failures/errors/skips, after explicit test-owned mail configuration and required-record/recipient handling. Enabled affected main/test/integration analysis, formatting and documentation checks pass. `AccountApplicationIntegrationTest.bootstrapUsesPersistedUuidAcrossPasswordOtpReadsAndInvalidationWhileOrdinaryLoginStaysNumeric` (historical bootstrap-stage name; the current combined UUID journey is `ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity`) executes real registration, unchanged numeric ordinary login, password bootstrap, actual email verification and generated-email-OTP bootstrap, UUID JWT/result assertions, subsequent HTTP bootstrap reads, successful-challenge removal and physical Redis session invalidation with unchanged persisted Account UUID/provenance/source-row identity. Its external Game Session discovery response and mail delivery remain controlled fixtures. Receiving R1147 at `89adf8951db3` on the qualified owner-diagnostic parent `584c336b55d0` passes all 229 Account service cases and the actual registration/password/OTP/bootstrap/session-invalidation native case, with zero failures/errors/skips and enabled affected analysis, formatting and documentation checks. Later parent carries retain the verified retention test and observation entries; their source attribution remains separate from this bootstrap proof. This is focused local proof; unfiltered native service execution and published-source CI/review remain separate obligations. This historical credential/result profile transition did not itself complete full bootstrap-journey identity convergence or canonical registry/profile qualification. The separately qualified bootstrap-connect-scope artifact also uses UUID identity. At this source, the Account-to-Entity character-discovery Account wire remained numeric; the final ordinary receiving cohort below converts that downstream Account reference to UUID while keeping Account SQL keys private. Ordinary control-UI/gameplay JWTs, shared forwarding/signed-routing intake, Social self-or-tenant authorization and APIs, public admission and gameplay activation remain outside this bootstrap-only transition. diff --git a/protos/entity-management/v1/entity_management_service.proto b/protos/entity-management/v1/entity_management_service.proto index 1cd5e858d6..8fbc886777 100644 --- a/protos/entity-management/v1/entity_management_service.proto +++ b/protos/entity-management/v1/entity_management_service.proto @@ -42,7 +42,7 @@ service EntityManagementService { // preseeded methods below remain restricted to PRESEEDED_ONLY; other policy values are // non-authorizing and fail with FAILED_PRECONDITION. The PLAYER_CREATED methods are a separate // source-bound read contract and do not authenticate their unsigned context or authorize the -// legacy numeric ListCharactersByAccount RPC for canonical gameplay. A valid ListPreseededRoster +// ordinary UUID-valued ListCharactersByAccount RPC for canonical gameplay. A valid ListPreseededRoster // response may contain zero actors; that is a successful lookup. These RPCs use canonical non-OK gRPC statuses // rather than in-response errors: malformed requests are INVALID_ARGUMENT, stale snapshots or // selections not present in the bound snapshot are FAILED_PRECONDITION, unauthorized callers are diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java index 32df02bf99..3f67966817 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java @@ -16,6 +16,8 @@ import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountState; import org.jooq.DSLContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @@ -23,6 +25,7 @@ @Repository public class AccountRepository { + private static final Logger logger = LoggerFactory.getLogger(AccountRepository.class); private final DSLContext dsl; private final AccountAuthoritySourceEvidenceRepository sourceEvidence; @@ -133,7 +136,9 @@ public List findByAccountUuids(List accountUuids) { accounts.add(account); } } catch (IllegalArgumentException | IllegalStateException ex) { - // Scalar UUID resolution rejects this row; a batch omits only that subject. + logger.warn( + "Omitting Account UUID batch row rejected by scalar readback; exceptionClass={}", + ex.getClass().getSimpleName()); } } return List.copyOf(accounts); 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 8c6c7df423..592381e0b4 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 @@ -63,6 +63,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.DataAccessException; import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.TransactionException; import tools.jackson.core.JacksonException; import tools.jackson.databind.JsonNode; import tools.jackson.databind.json.JsonMapper; @@ -1280,13 +1281,19 @@ private net.firedevops.firemud.shared.v1.ErrorDetail accountUuidReadbackUnavaila private long resolveAccountStorageIdForRpc(UUID accountUuid) { try { return accountService.resolveAccountStorageId(accountUuid); - } catch (IllegalStateException | DataAccessException ex) { - throw new AccountUuidReadbackUnavailableException(); + } catch (IllegalStateException | DataAccessException | TransactionException ex) { + logger.warn( + "Account UUID readback unavailable; exceptionClass={}", ex.getClass().getSimpleName()); + throw new AccountUuidReadbackUnavailableException(ex); } } private static final class AccountUuidReadbackUnavailableException extends RuntimeException { private static final long serialVersionUID = 1L; + + private AccountUuidReadbackUnavailableException(Throwable cause) { + super(cause); + } } private net.firedevops.firemud.shared.v1.ErrorDetail appError( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountRuntimeConsumerAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountRuntimeConsumerAuthWiringTest.java index 60b289c3f2..a20614e373 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountRuntimeConsumerAuthWiringTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountRuntimeConsumerAuthWiringTest.java @@ -47,6 +47,7 @@ class AccountRuntimeConsumerAuthWiringTest { private static final String IDENTITY_METHOD = "account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity"; private static final String NONPUBLIC_METHOD = "account.v1.AccountService/GetProfile"; + private static final String UPDATE_PROFILE_METHOD = "account.v1.AccountService/UpdateProfile"; private static final String REALM_GRANT_METHOD = "account.v1.AccountService/GetRealmAccessGrantForRuntime"; private static final String PRESENCE_METHOD = @@ -145,7 +146,7 @@ void exactSocialPeerReachesPresencePolicyHandlerWithoutBearerUnderBothYamlLayers } @Test - void bearerOnlyPresenceRequestReachesHandlerButIsDeniedWithoutSocialPeerUnderBothYamlLayers() { + void nonSocialPresenceRequestsReachHandlerButAreDeniedUnderBothYamlLayers() { for (boolean productionLayer : List.of(false, true)) { withConfiguredInterceptor( productionLayer, @@ -173,11 +174,19 @@ void bearerOnlyPresenceRequestReachesHandlerButIsDeniedWithoutSocialPeerUnderBot PresenceDispatchResult result = dispatchPresenceMethod(interceptor, service, null, bearer); + PresenceDispatchResult wrongNamespace = + dispatchPresenceMethod( + interceptor, + service, + "spiffe://firemud/ns/other/sa/social-groups-service", + null); - assertThat(result.handlerDispatched()).isTrue(); - assertThat(result.observer().completed).isTrue(); - assertThat(result.observer().response.getError().getCode()) - .isEqualTo("PERMISSION_DENIED"); + for (PresenceDispatchResult denied : List.of(result, wrongNamespace)) { + assertThat(denied.handlerDispatched()).isTrue(); + assertThat(denied.observer().completed).isTrue(); + assertThat(denied.observer().response.getError().getCode()) + .isEqualTo("PERMISSION_DENIED"); + } verifyNoInteractions(accountService); }); } @@ -341,6 +350,8 @@ private static void withConfiguredInterceptor( .contains(PRESENCE_METHOD) .contains(REALM_GRANT_METHOD) .doesNotContain(NONPUBLIC_METHOD); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .doesNotContain(UPDATE_PROFILE_METHOD); action.accept( context.getBean(AuthTokenInterceptor.class), context.getBean(JwtUtil.class)); }); 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 8d888ae8b5..f7bf465dcd 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 @@ -71,6 +71,7 @@ import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.transaction.CannotCreateTransactionException; class AccountGrpcServiceTest { private static final String WORKLOAD_NAMESPACE = "test"; @@ -154,7 +155,8 @@ void tearDown() { private static Stream accountUuidReadbackFailures() { return Stream.of( new IllegalStateException(ACCOUNT_UUID_READBACK_FAILURE), - new DataAccessResourceFailureException(ACCOUNT_UUID_READBACK_FAILURE)); + new DataAccessResourceFailureException(ACCOUNT_UUID_READBACK_FAILURE), + new CannotCreateTransactionException(ACCOUNT_UUID_READBACK_FAILURE)); } private static AccountService accountServiceWithUnavailableAccountUuidReadback( @@ -2040,6 +2042,55 @@ void getRealmAccessGrantForRuntimeFailsUnavailableOnMismatchedPrivateOwnerEviden observer)); assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals("", observer.response().getAccountId()); + } + + private static Stream mismatchedRealmGrantResults() { + String currentTime = Instant.now().toString(); + return Stream.of( + new RealmAccessGrantResult(42L, 8L, "demo", "preview", true, 3L, currentTime), + new RealmAccessGrantResult(42L, 7L, "other-world", "preview", true, 3L, currentTime), + new RealmAccessGrantResult(42L, 7L, "demo", "other-realm", true, 3L, currentTime), + new RealmAccessGrantResult(42L, 7L, "demo", "preview", true, 0L, currentTime), + new RealmAccessGrantResult(42L, 7L, "demo", "preview", true, -1L, currentTime), + new RealmAccessGrantResult(42L, 7L, "demo", "preview", true, 3L, null), + new RealmAccessGrantResult(42L, 7L, "demo", "preview", true, 3L, " "), + new RealmAccessGrantResult(42L, 7L, "demo", "preview", true, 3L, "not-an-instant"), + new RealmAccessGrantResult( + 42L, 7L, "demo", "preview", true, 3L, Instant.now().plusSeconds(60).toString())); + } + + @ParameterizedTest + @MethodSource("mismatchedRealmGrantResults") + void getRealmAccessGrantForRuntimeFailsUnavailableOnMismatchedAuthorityEvidence( + RealmAccessGrantResult result) { + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(42L); + Mockito.when(accountService.getRealmAccessGrantForRuntime(42L, 7L, "demo", "preview", "req-1")) + .thenReturn(result); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.getRealmAccessGrantForRuntime( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("preview") + .setRequestId("req-1") + .build(), + observer)); + + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals( + "Account authority unavailable; retry later", observer.response().getError().getMessage()); + assertEquals("", observer.response().getAccountId()); } @Test diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java index a4aefa1822..ca020dad8d 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.loggingadmin.repository.ModerationActionRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -53,7 +54,11 @@ void applyActionSavesEntity() throws Exception { ModerationActionDto result = service.applyAction(req); assertEquals(dto, result); - verify(repository).save(any(ModerationAction.class)); + ArgumentCaptor captor = ArgumentCaptor.forClass(ModerationAction.class); + verify(repository).save(captor.capture()); + assertEquals( + java.util.UUID.fromString("b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"), + captor.getValue().getAccountId()); } @Test From befc20142e734e486cf2d74cc9d84422b4b5c83c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:29:23 +1300 Subject: [PATCH 26/34] Preserve fixture identity and rebuild unreadable derived character graphs --- .../GameplaySessionAttestationService.java | 2 +- ...GameplaySessionAttestationServiceTest.java | 2 +- .../test/AccountRuntimeStubServerTest.java | 34 +++++++++ .../test/AccountRuntimeStubServer.java | 3 + .../service/impl/CharacterServiceImpl.java | 10 ++- .../impl/CharacterServiceImplTest.java | 70 +++++++++++++++++++ 6 files changed, 118 insertions(+), 3 deletions(-) diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java index 5392ff91b0..b9e0724b92 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java @@ -30,7 +30,7 @@ public String issueGameplaySessionAttestation( String normalizedRoomInstanceId = requireOptionalCanonicalRuntimeRoomId(roomInstanceId); requireText(tenantId, "tenantId"); requireText(sessionId, "sessionId"); - String canonicalAccountId = requireCanonicalAccountUuid(accountId, "accountId"); + String canonicalAccountId = JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); requireText(characterId, "characterId"); requireText(gameInstanceId, "gameInstanceId"); requireText(worldSlug, "worldSlug"); diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java index a13f6a8baa..bcd03f253b 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java @@ -48,7 +48,7 @@ void issueGameplaySessionAttestationRejectsNoncanonicalAccountUuidBeforeSigning( null }) { assertThrows( - GameplaySessionAttestationException.class, + IllegalArgumentException.class, () -> issuingService.issueGameplaySessionAttestation( "22", 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 e64a9abbc3..621b106c01 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 @@ -18,6 +18,40 @@ import org.junit.jupiter.api.Test; class AccountRuntimeStubServerTest { + @Test + void resetRetainsExplicitUuidRegistrationWithoutReauthentication() throws Exception { + try (var server = new AccountRuntimeStubServer(0)) { + server.mapAccountId("mapped@example.com", 7L); + var channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); + server.resetRuntimeState(); + + var profile = + stub.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(accountUuid).build()); + assertThat(profile.hasError()).isFalse(); + assertThat( + AccountProfileJson.parse(profile.getProfileJson(), "PRIVATE") + .presenceVisibilityPolicy()) + .isEqualTo("FRIENDS_ONLY"); + assertThat( + stub.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(accountUuid) + .setProfileJson("{\"presenceVisibilityPolicy\":\"PRIVATE\"}") + .build()) + .getSuccess()) + .isTrue(); + } finally { + channel.shutdownNow(); + } + } + } + @Test void runtimeEvidenceUsesTheExplicitTestClockInsteadOfAnExpiredCalendarFixture() throws Exception { var now = Instant.parse("2026-10-30T00:00:00Z"); 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 060d331a7b..179a111842 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 @@ -159,6 +159,9 @@ public void resetRuntimeState() { realmAccessGranted.set(true); profilesByAccountId.clear(); accountIdsByUuid.clear(); + accountIdsByEmail + .values() + .forEach(id -> accountIdsByUuid.put(accountUuidForTestFixture(id), id)); connectScopesById.clear(); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java index 14d2896cea..cc538538f4 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java @@ -18,6 +18,7 @@ import org.springframework.cache.CacheManager; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; +import org.springframework.data.redis.serializer.SerializationException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -80,7 +81,14 @@ public CharacterDto create( public CharacterDto getWithInventory(Long characterId) { Cache cache = cacheManager.getCache("characterGraph"); if (cache != null) { - CharacterDto cached = cache.get(characterId, CharacterDto.class); + CharacterDto cached; + try { + cached = cache.get(characterId, CharacterDto.class); + } catch (SerializationException ex) { + // Derived cache bytes do not establish ownership; rebuild through the strict SQL mapper. + cache.evict(characterId); + cached = null; + } if (cached != null) { cacheHitCounter.increment(); return cached; diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java index a611ba654a..ff96ab40df 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java @@ -20,9 +20,79 @@ import org.junit.jupiter.api.Test; import org.mapstruct.factory.Mappers; import org.mockito.Mockito; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; +import org.springframework.data.redis.serializer.SerializationException; class CharacterServiceImplTest { + @Test + void unreadableCachedGraphReloadsTheExactUuidOwnerWithoutSaving() { + CharacterRepository repo = Mockito.mock(CharacterRepository.class); + CacheManager manager = Mockito.mock(CacheManager.class); + Cache cache = Mockito.mock(Cache.class); + when(manager.getCache("characterGraph")).thenReturn(cache); + when(cache.get(1L, CharacterDto.class)) + .thenThrow(new SerializationException("retained graph format")); + Character character = new Character(); + character.setId(1L); + character.setTenantId(1L); + var owner = java.util.UUID.fromString("11111111-1111-4111-8111-111111111111"); + character.setAccountUuid(owner); + character.setPlayableStateKey("shared-live"); + character.setName("Current"); + when(repo.findWithInventoryById(1L)).thenReturn(Optional.of(character)); + var service = + new CharacterServiceImpl( + repo, + Mappers.getMapper(CharacterMapper.class), + manager, + new SimpleMeterRegistry(), + new PlayableStateKeyResolver(), + new ScopedCharacterResolver(repo, new PlayableStateKeyResolver())); + service.initMetrics(); + + CharacterDto dto = service.getWithInventory(1L); + + assertEquals(owner, dto.accountId()); + verify(cache).evict(1L); + verify(cache).put(1L, dto); + verify(repo, never()).save(any()); + } + + @Test + void unreadableCachedGraphStillRefusesAnUnresolvedStoredOwner() { + CharacterRepository repo = Mockito.mock(CharacterRepository.class); + CacheManager manager = Mockito.mock(CacheManager.class); + Cache cache = Mockito.mock(Cache.class); + when(manager.getCache("characterGraph")).thenReturn(cache); + when(cache.get(1L, CharacterDto.class)) + .thenThrow(new SerializationException("retained graph format")); + Character character = new Character(); + character.setId(1L); + character.setTenantId(1L); + character.setAccountId(42L); + character.setPlayableStateKey("shared-live"); + character.setName("Retained"); + when(repo.findWithInventoryById(1L)).thenReturn(Optional.of(character)); + var service = + new CharacterServiceImpl( + repo, + Mappers.getMapper(CharacterMapper.class), + manager, + new SimpleMeterRegistry(), + new PlayableStateKeyResolver(), + new ScopedCharacterResolver(repo, new PlayableStateKeyResolver())); + service.initMetrics(); + + assertThrows(IllegalArgumentException.class, () -> service.getWithInventory(1L)); + + verify(cache).evict(1L); + verify(cache, never()).put(any(), any()); + verify(repo, never()).save(any()); + assertEquals(42L, character.getAccountId()); + assertNull(character.getAccountUuid()); + } @Test void retainedUnresolvedOwnerCannotBeProjectedOrCached() { From e38f0480b56ee64dba47b3d2f472589be616f3f7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:33:10 +1300 Subject: [PATCH 27/34] Finish UUID receiving profile-policy reconciliation proof --- .../service/impl/AccountGrpcServiceTest.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) 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 3c56255ff0..9b4b80af8e 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 @@ -1378,7 +1378,18 @@ void profileMethodsRejectNoncanonicalAccountUuidBeforeResolution(String accountU } @ParameterizedTest - @ValueSource(strings = {"", "{", "null", "[]", "{\"presenceVisibilityPolicy\":\"UNKNOWN\"}", "{}", "{\"presenceVisibilityPolicy\":null}", "{\"presenceVisibilityPolicy\":17}", "{\"presenceVisibilityPolicy\":\"HIDDEN_STAFF\"}"}) + @ValueSource( + strings = { + "", + "{", + "null", + "[]", + "{\"presenceVisibilityPolicy\":\"UNKNOWN\"}", + "{}", + "{\"presenceVisibilityPolicy\":null}", + "{\"presenceVisibilityPolicy\":17}", + "{\"presenceVisibilityPolicy\":\"HIDDEN_STAFF\"}" + }) void updateProfileRejectsMalformedJsonAndPolicyWithInvalidArgument(String profileJson) { AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = From 82db56df12a36eba16b5994981b7794f330132d3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:52:18 +1300 Subject: [PATCH 28/34] Prove bootstrap HTTP UUID forwarding through real Entity mTLS storage --- services/account-service/build.gradle.kts | 6 + ...rUuidEntityCompositionIntegrationTest.java | 604 ++++++++++++++++++ 2 files changed, 610 insertions(+) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 3055dc48e3..45200b4482 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -88,6 +88,8 @@ dependencies { testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) integrationTestImplementation(project(path = ":game-session-service", configuration = "gameSessionClassesProof")) + integrationTestImplementation(project(path = ":entity-management-service", configuration = "entityClassesProof")) + integrationTestImplementation(testFixtures(project(":common-test-support"))) integrationTestImplementation(project(":social-groups-service")) integrationTestImplementation(testFixtures(project(":account-service"))) integrationTestImplementation(testFixtures(project(":logging-admin-service"))) @@ -163,6 +165,10 @@ tasks.named("integrationTest") { // Composition fixtures load Game Session and Common Saga migrations directly from the filesystem. inputs.dir(project(":game-session-service").file("src/main/resources/db/migration")) .withPathSensitivity(PathSensitivity.RELATIVE) + val entityMigrationDirectory = + project(":entity-management-service").file("src/main/resources/db/migration") + inputs.dir(entityMigrationDirectory).withPathSensitivity(PathSensitivity.RELATIVE) + systemProperty("firemud.entity-management.migration-directory", entityMigrationDirectory.absolutePath) inputs.dir(project(":common-saga").file("src/main/resources/db/migration/saga")) .withPathSensitivity(PathSensitivity.RELATIVE) val loggingArtifacts = loggingAdminIntegrationTestArtifacts.artifactFiles diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java new file mode 100644 index 0000000000..3c7e1979d8 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java @@ -0,0 +1,604 @@ +package net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.io.IOException; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateEncodingException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; +import net.firedevops.firemud.entitymanagement.mapper.CharacterMapper; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.PlayableStateKeyResolver; +import net.firedevops.firemud.entitymanagement.service.ScopedCharacterResolver; +import net.firedevops.firemud.entitymanagement.service.impl.CharacterServiceImpl; +import net.firedevops.firemud.entitymanagement.service.impl.EntityManagementGrpcService; +import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.test.GatewayTestProperties; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.mapstruct.factory.Mappers; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.cache.concurrent.ConcurrentMapCacheManager; +import org.springframework.http.HttpHeaders; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Composes real Account bootstrap HTTP with its mTLS Entity roster client and real Entity storage. + * Game Session target reads, test-owned membership rows, and test PKI are controlled fixtures; this + * proves neither World-owned active lifecycle nor public admission or first OPEN. Entity RPCs not + * used by ordinary roster reads remain mocked. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = WebEnvironment.RANDOM_PORT, + classes = AccountServiceApplication.class, + properties = { + "spring.config.import=classpath:account-main-application.yml", + "spring.grpc.server.port=0", + "firemud.grpc.workload-namespace=test", + GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, + "firemud.mail.verification-url=https://account.test/verify-email?token=%s" + }) +class BootstrapCharacterUuidEntityCompositionIntegrationTest { + private static final String TEST_NAMESPACE = "test"; + private static final String TEST_ACCOUNT_PEER = "spiffe://firemud/ns/test/sa/account-service"; + private static final String TEST_ENTITY_PEER = + "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final long TARGET_TENANT_ID = 1L; + private static final long TARGET_GAME_INSTANCE_ID = 44L; + private static final String WORLD_SLUG = "uuid-bootstrap-proof"; + private static final String REALM_SLUG = "production"; + private static final UUID TARGET_REALM_ID = + UUID.fromString("d8f8de2e-89fd-4432-8cb4-93f241f56af6"); + private static final UUID TARGET_NAMESPACE_ID = + UUID.fromString("f711c0c9-c1fc-46fb-8ff2-1af7c4d96a67"); + private static final long RETAINED_NUMERIC_ACCOUNT_ID = 98765L; + + private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); + private static final Path PKI_DIRECTORY = createTemporaryDirectory(); + private static final LoopbackMtlsTestPki.Pki TEST_PKI = createTestPki(); + private static final CommonGrpcClientProperties ACCOUNT_CLIENT_TLS = createAccountClientTls(); + private static final PostgreSQLContainer entityPostgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static PostgreSQLContainer accountPostgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private static volatile EntityRuntime entityRuntime; + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, accountPostgres, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + registry.add("firemud.services.entity-management-service", () -> entityServiceTarget()); + registry.add("FIREMUD_GRPC_CERT_CHAIN_PATH", ACCOUNT_CLIENT_TLS::getCertChain); + registry.add("FIREMUD_GRPC_PRIVATE_KEY_PATH", ACCOUNT_CLIENT_TLS::getPrivateKey); + registry.add("FIREMUD_GRPC_CA_CERT_PATH", ACCOUNT_CLIENT_TLS::getCaCert); + } + + @LocalServerPort private int accountHttpPort; + @Autowired private DSLContext accountDsl; + @Autowired private JwtUtil jwtUtil; + + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + + private final JsonMapper jsonMapper = JsonMapper.builder().build(); + + @org.junit.jupiter.api.AfterAll + static void stopEntityRuntime() throws InterruptedException { + EntityRuntime runtime = entityRuntime; + if (runtime != null) { + runtime.server().shutdownNow(); + assertThat(runtime.server().awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + runtime.meters().close(); + } + if (entityPostgres.isRunning()) { + entityPostgres.stop(); + } + } + + @org.junit.jupiter.api.Test + void bootstrapCharactersUsePersistedUuidAcrossHttpAndRealEntityOwnerReads() throws Exception { + stubControlledCurrentTarget(); + + String suffix = UUID.randomUUID().toString().substring(0, 8); + TestAccount ownerA = registerAccount("uuid-owner-a-" + suffix); + TestAccount ownerB = registerAccount("uuid-owner-b-" + suffix); + assertThat(ownerA.accountUuid()).isNotEqualTo(ownerB.accountUuid()); + seedAdmittingMembership(ownerA.storageId()); + seedAdmittingMembership(ownerB.storageId()); + seedActiveSubscription(ownerA.storageId()); + + EntityRuntime entity = requireEntityRuntime(); + String ownerACharacterName = "owned-by-a-" + suffix; + String ownerBCharacterName = "owned-by-b-" + suffix; + String wrongTenantCharacterName = "wrong-tenant-a-" + suffix; + var ownerACharacter = + saveOrdinaryCharacter( + entity, TARGET_TENANT_ID, ownerA.accountUuid(), ownerACharacterName, "shared-live"); + var ownerBCharacter = + saveOrdinaryCharacter( + entity, TARGET_TENANT_ID, ownerB.accountUuid(), ownerBCharacterName, "shared-live"); + var wrongTenantCharacter = + saveOrdinaryCharacter( + entity, + TARGET_TENANT_ID + 1, + ownerA.accountUuid(), + wrongTenantCharacterName, + "shared-live"); + + assertOrdinaryUuidRowIsQuarantined(entity, ownerACharacter.getId(), ownerA.accountUuid()); + assertOrdinaryUuidRowIsQuarantined(entity, ownerBCharacter.getId(), ownerB.accountUuid()); + assertOrdinaryUuidRowIsQuarantined(entity, wrongTenantCharacter.getId(), ownerA.accountUuid()); + + var retainedBefore = retainedNumericOwnerRow(entity); + assertThat(retainedBefore).hasSize(1); + + String ownerAToken = issuePlayerBootstrap(ownerA); + String ownerBToken = issuePlayerBootstrap(ownerB); + String ownerAScope = discoverConnectScope(ownerA, ownerAToken); + String ownerBScope = discoverConnectScope(ownerB, ownerBToken); + + JsonNode ownerACharacters = listBootstrapCharacters(ownerAToken, ownerAScope); + JsonNode ownerBCharacters = listBootstrapCharacters(ownerBToken, ownerBScope); + + assertThat(characterNames(ownerACharacters)).containsExactly(ownerACharacterName); + assertThat(characterNames(ownerACharacters)) + .doesNotContain(ownerBCharacterName, wrongTenantCharacterName); + assertThat(characterNames(ownerBCharacters)).containsExactly(ownerBCharacterName); + assertThat(characterNames(ownerBCharacters)).doesNotContain(ownerACharacterName); + + var retainedAccountIdRequest = + ListCharactersByAccountRequest.newBuilder() + .setTenantId(Long.toString(TARGET_TENANT_ID)) + .setAccountId(Long.toString(RETAINED_NUMERIC_ACCOUNT_ID)) + .setGameInstanceId(Long.toString(TARGET_GAME_INSTANCE_ID)) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build(); + var retainedOwnerResponse = listCharactersDirectlyAsAccount(retainedAccountIdRequest); + assertThat(retainedOwnerResponse.hasError()).isTrue(); + assertThat(retainedOwnerResponse.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(retainedOwnerResponse.getCharactersList()).isEmpty(); + assertThat(retainedNumericOwnerRow(entity)).isEqualTo(retainedBefore); + } + + private TestAccount registerAccount(String username) throws Exception { + String email = username + "@example.com"; + HttpRequest request = + HttpRequest.newBuilder(URI.create(accountBaseUrl() + "/accounts")) + .header(HttpHeaders.CONTENT_TYPE, "application/json") + .POST( + HttpRequest.BodyPublishers.ofString( + jsonMapper.writeValueAsString( + Map.of("username", username, "email", email, "password", "password123")))) + .build(); + HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + assertThat(response.statusCode()).as(response.body()).isEqualTo(200); + + String responseUuid = jsonMapper.readTree(response.body()).path("data").path("id").asText(); + UUID accountUuid = UUID.fromString(responseUuid); + Number accountId = + accountDsl + .resultQuery("SELECT id FROM accounts WHERE email = ?", email) + .fetchOne(0, Number.class); + assertThat(accountId).isNotNull(); + long storageId = accountId.longValue(); + assertThat( + accountDsl + .resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", storageId) + .fetchOne(0, UUID.class)) + .isEqualTo(accountUuid); + assertThat( + accountDsl + .resultQuery( + "SELECT account_uuid_source_numeric_id FROM accounts WHERE id = ?", storageId) + .fetchOne(0, Long.class)) + .isEqualTo(storageId); + assertThat( + accountDsl + .resultQuery("SELECT account_uuid_provenance FROM accounts WHERE id = ?", storageId) + .fetchOne(0, String.class)) + .isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + return new TestAccount(username, email, storageId, accountUuid); + } + + private void seedAdmittingMembership(long accountId) { + // This is test-owned Account state for the existing roster guard, not canonical membership + // proof. + accountDsl.execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, TRUE, 'ACTIVE', 1, 1, 'SEEDED_DEMO')", + accountId, + TARGET_TENANT_ID); + } + + private void seedActiveSubscription(long accountId) { + accountDsl.execute( + "INSERT INTO subscription " + + "(account_id, plan_id, status, tenant_id, entitlement_version) " + + "VALUES (?, 'uuid-bootstrap-composition', 'active', ?, 1)", + accountId, + TARGET_TENANT_ID); + } + + private String issuePlayerBootstrap(TestAccount account) throws Exception { + HttpRequest request = + HttpRequest.newBuilder(URI.create(accountBaseUrl() + "/auth/player-bootstrap")) + .header(HttpHeaders.CONTENT_TYPE, "application/json") + .POST( + HttpRequest.BodyPublishers.ofString( + jsonMapper.writeValueAsString( + Map.of("accountIdentifier", account.username(), "secret", "password123")))) + .build(); + HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + assertThat(response.statusCode()).as(response.body()).isEqualTo(200); + JsonNode data = jsonMapper.readTree(response.body()).path("data"); + assertThat(data.path("accountId").asText()).isEqualTo(account.accountUuid().toString()); + String bootstrapToken = data.path("bootstrapToken").asText(); + var claims = jwtUtil.parseToken(bootstrapToken).getPayload(); + assertThat(claims.getSubject()).isEqualTo(account.accountUuid().toString()); + assertThat(claims.get("accountId", String.class)).isEqualTo(account.accountUuid().toString()); + return bootstrapToken; + } + + private String discoverConnectScope(TestAccount account, String bootstrapToken) throws Exception { + HttpRequest request = + HttpRequest.newBuilder( + URI.create(accountBaseUrl() + "/auth/bootstrap/worlds/" + WORLD_SLUG + "/realms")) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + bootstrapToken) + .GET() + .build(); + HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + assertThat(response.statusCode()).as(response.body()).isEqualTo(200); + JsonNode realms = jsonMapper.readTree(response.body()).path("data"); + assertThat(realms.isArray()).isTrue(); + assertThat(realms.size()).isEqualTo(1); + JsonNode realm = realms.get(0); + assertThat(realm.path("tenantId").asLong()).isEqualTo(TARGET_TENANT_ID); + String scope = realm.path("connectScopeId").asText(); + var claims = jwtUtil.parseToken(scope).getPayload(); + assertThat(claims.getSubject()).isEqualTo(account.accountUuid().toString()); + assertThat(claims.get("accountId", String.class)).isEqualTo(account.accountUuid().toString()); + return scope; + } + + private JsonNode listBootstrapCharacters(String bootstrapToken, String connectScopeId) + throws Exception { + String encodedScope = URLEncoder.encode(connectScopeId, StandardCharsets.UTF_8); + HttpRequest request = + HttpRequest.newBuilder( + URI.create( + accountBaseUrl() + + "/auth/bootstrap/worlds/" + + WORLD_SLUG + + "/realms/" + + REALM_SLUG + + "/characters?connectScopeId=" + + encodedScope)) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + bootstrapToken) + .GET() + .build(); + HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + assertThat(response.statusCode()).as(response.body()).isEqualTo(200); + return jsonMapper.readTree(response.body()).path("data"); + } + + private ListCharactersByAccountResponse listCharactersDirectlyAsAccount( + ListCharactersByAccountRequest request) throws Exception { + EntityRuntime runtime = requireEntityRuntime(); + var identity = TEST_PKI.identity("account"); + ManagedChannel channel = + NettyChannelBuilder.forAddress("localhost", runtime.server().getPort()) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(TEST_PKI.caCertificate()) + .keyManager( + identity.privateKey(), identity.certificate(), TEST_PKI.caCertificate()) + .build()) + .intercept(new GrpcServerPeerIdentityClientInterceptor(TEST_ENTITY_PEER)) + .build(); + try { + return EntityManagementServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .listCharactersByAccount(request); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private void stubControlledCurrentTarget() { + var realm = + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug(WORLD_SLUG) + .setRealmSlug(REALM_SLUG) + .setDisplayName("Controlled UUID composition target") + .setTenantId(Long.toString(TARGET_TENANT_ID)) + .setGameInstanceId(Long.toString(TARGET_GAME_INSTANCE_ID)) + .setRealmId(TARGET_REALM_ID.toString()) + .setPlayableStateNamespaceId(TARGET_NAMESPACE_ID.toString()) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build(); + var pointer = + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug(WORLD_SLUG) + .setRealmSlug(REALM_SLUG) + .setTenantId(Long.toString(TARGET_TENANT_ID)) + .setGameInstanceId(Long.toString(TARGET_GAME_INSTANCE_ID)) + .setRealmId(TARGET_REALM_ID.toString()) + .setPlayableStateNamespaceId(TARGET_NAMESPACE_ID.toString()) + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build(); + Mockito.when(gameSessionClient.listGameplayRealms(WORLD_SLUG)).thenReturn(List.of(realm)); + Mockito.when(gameSessionClient.getAdmissionPointer(TARGET_TENANT_ID, WORLD_SLUG, REALM_SLUG)) + .thenReturn(pointer); + } + + private static net.firedevops.firemud.entitymanagement.entity.Character saveOrdinaryCharacter( + EntityRuntime runtime, + long tenantId, + UUID accountUuid, + String name, + String playableStateKey) { + var character = new net.firedevops.firemud.entitymanagement.entity.Character(); + character.setTenantId(tenantId); + character.setAccountUuid(accountUuid); + character.setPlayableStateKey(playableStateKey); + character.setName(name); + return runtime.characterRepository().save(character); + } + + private static void assertOrdinaryUuidRowIsQuarantined( + EntityRuntime runtime, long characterId, UUID accountUuid) { + var persisted = runtime.characterRepository().findById(characterId).orElseThrow(); + assertThat(persisted.getAccountUuid()).isEqualTo(accountUuid); + assertThat(persisted.getAccountId()).isNull(); + assertThat(persisted.getActorIdentity().status()).isEqualTo(ActorIdentityStatus.QUARANTINED); + assertThat(persisted.getActorIdentity().tenantUuid()).isNull(); + assertThat(persisted.getActorIdentity().playableStateNamespaceId()).isNull(); + } + + private static List> retainedNumericOwnerRow(EntityRuntime runtime) { + return runtime + .jdbc() + .queryForList( + "SELECT *, xmin::text AS retained_xmin FROM characters WHERE account_id = ?", + RETAINED_NUMERIC_ACCOUNT_ID); + } + + private static List characterNames(JsonNode characters) { + return java.util.stream.StreamSupport.stream(characters.spliterator(), false) + .map(character -> character.path("characterName").asText()) + .toList(); + } + + private String accountBaseUrl() { + return "http://localhost:" + accountHttpPort; + } + + private static String entityServiceTarget() { + return "localhost:" + requireEntityRuntime().server().getPort(); + } + + private static synchronized EntityRuntime requireEntityRuntime() { + if (entityRuntime != null) { + return entityRuntime; + } + try { + if (!entityPostgres.isRunning()) { + entityPostgres.start(); + } + var dataSource = + new DriverManagerDataSource( + entityPostgres.getJdbcUrl(), + entityPostgres.getUsername(), + entityPostgres.getPassword()); + Path migrationDirectory = + Path.of(System.getProperty("firemud.entity-management.migration-directory", "")); + if (!Files.isDirectory(migrationDirectory)) { + throw new IllegalStateException( + "Entity migration directory is unavailable: " + migrationDirectory); + } + entityMigrationConfiguration(dataSource, migrationDirectory) + .target(MigrationVersion.fromVersion("1023")) + .load() + .migrate(); + var jdbc = new JdbcTemplate(dataSource); + jdbc.update( + "INSERT INTO characters (tenant_id, account_id, name) VALUES (?, ?, ?)", + TARGET_TENANT_ID, + RETAINED_NUMERIC_ACCOUNT_ID, + "retained-numeric-owner"); + entityMigrationConfiguration(dataSource, migrationDirectory).load().migrate(); + + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + var repository = new CharacterRepository(dsl); + var stateKeys = new PlayableStateKeyResolver(); + var meters = new SimpleMeterRegistry(); + var characterService = + new CharacterServiceImpl( + repository, + Mappers.getMapper(CharacterMapper.class), + new ConcurrentMapCacheManager("characterGraph"), + meters, + stateKeys, + new ScopedCharacterResolver(repository, stateKeys)); + var receiver = + new EntityManagementGrpcService( + Mockito.mock(net.firedevops.firemud.entitymanagement.service.PingService.class), + characterService, + Mockito.mock(net.firedevops.firemud.entitymanagement.service.ActorStateService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.ActorConditionMutationService + .class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService + .class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.EquipmentService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.InventoryService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.ContainerService.class), + Mockito.mock(net.firedevops.firemud.entitymanagement.service.RoomEntityService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.RuntimeInstanceCleanupService + .class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.impl + .EntityMutationEffectReplayService.class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.EntityUpgradeValidationService + .class), + Mockito.mock( + net.firedevops.firemud.entitymanagement.service.EntityTemplateReferenceService + .class), + Mockito.mock( + net.firedevops.firemud.common.security.GameplaySessionAttestationService.class), + meters, + Mockito.mock( + net.firedevops.firemud.entitymanagement.effect.EffectPayloadParser.class), + TEST_NAMESPACE); + var entityIdentity = TEST_PKI.identity("entity"); + Server server = + NettyServerBuilder.forPort(0) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + entityIdentity.privateKey(), entityIdentity.certificate())) + .trustManager(TEST_PKI.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(receiver, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + entityRuntime = new EntityRuntime(repository, jdbc, server, meters); + return entityRuntime; + } catch (IOException | RuntimeException failure) { + if (entityPostgres.isRunning()) { + entityPostgres.stop(); + } + throw new IllegalStateException( + "Could not start the real Entity mTLS owner fixture", failure); + } + } + + private static FluentConfiguration entityMigrationConfiguration( + DriverManagerDataSource dataSource, Path migrationDirectory) { + FluentConfiguration configuration = + Flyway.configure() + .dataSource(dataSource) + .locations("filesystem:" + migrationDirectory) + .placeholders(Map.of("serviceSchema", "public")); + configuration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + return configuration; + } + + private static Path createTemporaryDirectory() { + try { + return Files.createTempDirectory("firemud-account-entity-composition-"); + } catch (Exception failure) { + throw new ExceptionInInitializerError(failure); + } + } + + private static LoopbackMtlsTestPki.Pki createTestPki() { + try { + return LoopbackMtlsTestPki.create( + PKI_DIRECTORY, + "Account-to-Entity composition proof CA", + new LoopbackMtlsTestPki.IdentitySpec("entity", TEST_ENTITY_PEER, true), + new LoopbackMtlsTestPki.IdentitySpec("account", TEST_ACCOUNT_PEER, false)); + } catch (Exception failure) { + throw new ExceptionInInitializerError(failure); + } + } + + private static CommonGrpcClientProperties createAccountClientTls() { + try { + return TEST_PKI.clientProperties(PKI_DIRECTORY, TEST_PKI.identity("account")); + } catch (CertificateEncodingException | java.io.IOException failure) { + throw new ExceptionInInitializerError(failure); + } + } + + private record TestAccount(String username, String email, long storageId, UUID accountUuid) {} + + private record EntityRuntime( + CharacterRepository characterRepository, + JdbcTemplate jdbc, + Server server, + SimpleMeterRegistry meters) {} +} From b4a93159b9680261425bb1c574c7ac230de48f5f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:44:08 +1300 Subject: [PATCH 29/34] docs: align account identity status with UUID receiving --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index a657a1dece..282b19a233 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -440,7 +440,7 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | +| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The historical initial unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped when Docker was unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Previously merged bootstrap credential and connect-scope artifacts use the Account UUID. Ordinary password/OTP results, JWT subjects and profile/export identity fields also use that UUID in this receiving source; tenant IDs remain numeric and full portable export is not implemented. The [ordinary UUID receiving record](#ordinary-uuid-issuer-and-receiving) owns the current implementation and proof limits. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and alone do not qualify the later UUID receiving source or production gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | From 411aef5c9f0560267b12da38f1690eb75e76a59a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 19:54:14 +1300 Subject: [PATCH 30/34] Check the fresh room inventory reply after dropping an item --- .../gamesession/CommunicationWebSocketCrossServiceTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index 593a11476e..207129bfd2 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 @@ -572,9 +572,10 @@ void websocketItemLoopMovesRoomItemThroughInventoryAndBack() throws Exception { "Room Inventory:", "- Torch [torch#1] (A small torch)")) .contains("Room Inventory:"); + int finalInventoryCount = client.responseCount(); client.send("INV HERE"); - client.awaitContains("Room Inventory:"); - client.awaitContains("- Torch [torch#1] (A small torch)"); + client.awaitTranscriptContainingAllAfter( + finalInventoryCount, "Room Inventory:", "- Torch [torch#1] (A small torch)"); GameplayEntityAssertions.assertDrop( entityStub().lastDropRequest(), String.valueOf(TENANT_ID), From c7acb662554238ec15e1cc926fa4c5cd7e37c76f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 20:54:19 +1300 Subject: [PATCH 31/34] Distinguish unresolved stored owners and clarify UUID review proof --- .../account-service/runtime-and-data.md | 2 +- .../service/impl/CharacterServiceImpl.java | 4 ++ .../impl/CharacterServiceImplTest.java | 39 +++++++++++++++++-- ...ionAccountCrossServiceIntegrationTest.java | 2 +- 4 files changed, 42 insertions(+), 5 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index d85bf9f0ac..cd41e4b505 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -54,7 +54,7 @@ The source preparation also includes unregistered, caller-transaction-bound crea Account's actor-staging eligibility owner read is a read-only, same-namespace Entity workload RPC gated off by default. Under one repeatable-read Account transaction it verifies persisted Account UUID/provenance, current Account membership and pair authority, fresh Game Design tenant-source evidence, and the current membership event/checkpoint, then returns digest-sealed evidence scoped to `PUBLIC_PRODUCTION_STAGING_ONLY`. It reports an eligible or ineligible source snapshot but creates no membership, actor assignment, JOIN, PLAY, or gameplay admission. The staged foundation passed 43 focused Account tests and 92 shared-evidence tests with no failures or skips, plus source generation and Account integration-source compilation. PostgreSQL migration/persistence proof sources are included but physical PostgreSQL and live runtime execution remain unrun; the RPC is not runtime-ready or admission authority. -Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST/gRPC and the Account component of current Account/profile-local and legacy tenant exports expose that UUID through `AccountDto.id`; the mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and registration audit payloads use the same UUID. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, Account-issued JWT `sub`/`accountId` claims, and `ProfileDto.accountId` carry the persisted UUID. Account resolves UUIDs to private numeric rows only for local storage operations; the row is not an API identity. REST-specific update DTOs preserve the UUID path/body contract, and internal/gRPC updates and caller binding use UUIDs. Tenant IDs and profile tenant identifiers retain their current representation. The final ordinary receiving proof and its limits are recorded in the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). The current export remains partial Account/profile-local data, not the canonical portable export. [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. +Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST exposes that UUID through `AccountDto.id`, while registration gRPC exposes it through `CreateAccountResponse.account_id`; the Account component of current Account/profile-local and legacy tenant exports also carries the UUID. The mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and registration audit payloads use the same UUID. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, Account-issued JWT `sub`/`accountId` claims, and `ProfileDto.accountId` carry the persisted UUID. Account resolves UUIDs to private numeric rows only for local storage operations; the row is not an API identity. REST-specific update DTOs preserve the UUID path/body contract, and internal/gRPC updates and caller binding use UUIDs. Tenant IDs and profile tenant identifiers retain their current representation. The final ordinary receiving proof and its limits are recorded in the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). The current export remains partial Account/profile-local data, not the canonical portable export. [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. The account lifecycle state machine, global deletion preconditions, account-scoped versus tenant-scoped portable-data export split, separate safety-restriction lifecycles, hosting-billing authority, and future-marketplace `purchase_entitlement` substrate are the canonical target design. The current service has live identity/authentication, profile, external-link persistence, recovery/verification, payment, subscription, notification, and virtual-currency foundations, but lifecycle state transitions, genuine provider authentication, cross-service export, retained-record handling, complete account lock/platform-ban enforcement, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial. The current account export returns only Account and profile rows, the tenant export includes excessive global Account fields, and DeleteAccount preserves its JOIN and billing denials before failing closed without deleting child rows; AccountRepository retains its independent hard-delete guard. A complete retained-data lifecycle remains absent. Those behaviors directly conflict with [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and the bounded erasure workflow below. diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java index cc538538f4..dc6008486a 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java @@ -182,6 +182,10 @@ private static void requireAccountOwner(java.util.UUID accountId) { } private CharacterDto toDto(Character character) { + java.util.UUID accountUuid = character.getAccountUuid(); + if (accountUuid == null || accountUuid.equals(new java.util.UUID(0L, 0L))) { + throw new IllegalStateException("Persisted character has no valid Account UUID"); + } CharacterDto dto = characterMapper.toDto(character); return new CharacterDto( dto.id(), diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java index ff96ab40df..a980921574 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java @@ -85,7 +85,7 @@ void unreadableCachedGraphStillRefusesAnUnresolvedStoredOwner() { new ScopedCharacterResolver(repo, new PlayableStateKeyResolver())); service.initMetrics(); - assertThrows(IllegalArgumentException.class, () -> service.getWithInventory(1L)); + assertThrows(IllegalStateException.class, () -> service.getWithInventory(1L)); verify(cache).evict(1L); verify(cache, never()).put(any(), any()); @@ -118,9 +118,9 @@ void retainedUnresolvedOwnerCannotBeProjectedOrCached() { when(repo.findByTenantIdAndPlayableStateKeyAndNameIgnoreCase(1L, "shared-live", "Retained")) .thenReturn(Optional.of(retained)); - assertThrows(IllegalArgumentException.class, () -> service.getWithInventory(1L)); + assertThrows(IllegalStateException.class, () -> service.getWithInventory(1L)); assertThrows( - IllegalArgumentException.class, + IllegalStateException.class, () -> service.findByGameplayScopeAndName( 1L, "live", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "Retained")); @@ -131,6 +131,39 @@ void retainedUnresolvedOwnerCannotBeProjectedOrCached() { verify(repo, never()).save(any()); } + @Test + void retainedNilOwnerCannotBeProjectedOrCached() { + CharacterRepository repo = Mockito.mock(CharacterRepository.class); + CharacterMapper mapper = Mockito.mock(CharacterMapper.class); + var cacheManager = new ConcurrentMapCacheManager("characterGraph"); + CharacterServiceImpl service = + new CharacterServiceImpl( + repo, + mapper, + cacheManager, + new SimpleMeterRegistry(), + new PlayableStateKeyResolver(), + new ScopedCharacterResolver(repo, new PlayableStateKeyResolver())); + service.initMetrics(); + Character retained = Mockito.spy(new Character()); + retained.setId(1L); + retained.setTenantId(1L); + retained.setAccountId(42L); + var nilUuid = new java.util.UUID(0L, 0L); + // Simulate an invalid repository projection without weakening the entity setter guard. + Mockito.doReturn(nilUuid).when(retained).getAccountUuid(); + retained.setPlayableStateKey("shared-live"); + retained.setName("Retained"); + when(repo.findWithInventoryById(1L)).thenReturn(Optional.of(retained)); + + assertThrows(IllegalStateException.class, () -> service.getWithInventory(1L)); + + assertNull(cacheManager.getCache("characterGraph").get(1L)); + assertEquals(nilUuid, retained.getAccountUuid()); + verify(mapper, never()).toDto(any()); + verify(repo, never()).save(any()); + } + @Test void gainExperienceLevelsUp() { CharacterRepository repo = Mockito.mock(CharacterRepository.class); diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index d79dd9ce51..b08321835e 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -572,7 +572,7 @@ void telnetSecondConnectionTakesOverGameplayBinding() throws Exception { } @Test - void telnetCommunicationMatchesCanonicalTranscriptsWithoutSession() throws Exception { + void telnetCommunicationMatchesCanonicalTranscripts() throws Exception { ensureTestServicesStarted(); entityStub().setRoomEntities(ChatTestFixtures.sampleEntities()); seedLiveTargetSession(); From 66adeeee09808ed110675afb5ebc785757782a71 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:46:35 +1300 Subject: [PATCH 32/34] Tighten UUID receiving proof setup and retained-context documentation --- .../implementation-tracking/player-access-and-session.md | 4 ++-- ...trapCharacterUuidEntityCompositionIntegrationTest.java | 8 ++++++-- .../gamesession/GameSessionLoginIntegrationTest.java | 5 ++++- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index d651fd5ccf..e87f53a531 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -540,7 +540,7 @@ Account owns canonical identity and owner resolution; Social consumes that ident #### Ordinary UUID issuer and receiving -The local receiving source converges ordinary password/verified-email credentials, UUID subject/account binding, shared intake/forwarding, Account owner reads, gameplay LOGIN/PLAY/context carriers, moderation selectors and ordinary Entity roster ownership on actual canonical Account UUIDs. Account alone resolves its UUID to private storage identity. Durable communication rejection retains player error output through delivery and replay. No numeric fallback, guessed ownership or retained-data rewrite is supplied. Canonical identity and authorization remain with the [Account API](../../architecture/microservices/account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity), [JWT contract](../../architecture/system-architecture-jwt-and-token-contracts.md#jwt-claim-contract-normative) and owning service contracts. +The local receiving source converges ordinary password/verified-email credentials, UUID subject/account binding, shared intake/forwarding, Account owner reads, gameplay LOGIN/PLAY/context carriers, moderation selectors and ordinary Entity roster ownership on actual canonical Account UUIDs. Account alone resolves its UUID to private storage identity. Durable communication rejection retains player error output through delivery and replay. No numeric fallback, guessed ownership or retained-data rewrite is supplied. Retained session contexts with numeric, malformed or nil Account identity fail closed on lookup, replacement and deletion until their existing TTL expires (the default is 3,600,000 ms); callers reusing those session IDs can receive authentication-service-unavailable during that interval. This transition grants no blanket `sessionctx:*` flush or deletion; any explicit reset still follows the canonical reset and recovery owner. Canonical identity and authorization remain with the [Account API](../../architecture/microservices/account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity), [JWT contract](../../architecture/system-architecture-jwt-and-token-contracts.md#jwt-claim-contract-normative) and owning service contracts. Final UUID-positive Login/WebSocket live and recent presence, AFK/reconnect, Account-native and transport/item/communication/load proof postimages are preserved. R1273 passes 462 Entity unit and 135 native cases, with no failures, errors or skips. R1274 uses fresh images for actual Account `Authenticate` to Entity UUID seeding and direct LOGIN/PLAY/LOOK, then verifies authenticated cleanup leaves zero resources; this runtime proof is at `671a9e3e205ce39300b93aea03871efe890c5549`. R1279 exercises the actual certificate-derived mTLS receiver through the Entity service, mapper and PostgreSQL: positive, wrong-owner, wrong-tenant, unresolved-owner, wrong-service and wrong-namespace cases all pass. The final tree at `026c549985ccf5c461dba0ab8c026f525ce7014a` exactly matches the fully qualified source tree at `81fcde7c4049b0be4aa67c1b09f5d4c68db667f2`; only work partitioning differs. These focused results do not qualify the whole pipeline, production PKI, public admission, or current remote CI. Controlled Social transport proof still does not establish genuine Social sender-handoff acceptance or player-safe chat; the [Social API limits](../../architecture/microservices/social-groups-service/api-contracts.md#implementation-status) remain. @@ -568,7 +568,7 @@ The maintained integration path uses the real Account/Redis/GameInstance/downstr ### Admission and Gameplay Binding -Trusted proxy, first-party, bootstrap, and connect-token inputs fail closed before they can establish or preserve routing state. Signed actor identity requires positive, matching `sub` and `accountId` claims. Gameplay routing requires a complete positive bundle of `tenantId`, `gameInstanceId`, `worldSlug`, `realmSlug`, and `pointerVersion`; blank slugs, partial bundles, stale pointers, mismatched world/realm targets, and malformed claims are rejected before routing reuse or persistence. +Trusted proxy, first-party, bootstrap, and connect-token inputs fail closed before they can establish or preserve routing state. Signed actor identity requires canonical, matching non-nil UUID `sub` and `accountId` claims. Gameplay routing requires a complete positive bundle of `tenantId`, `gameInstanceId`, `worldSlug`, `realmSlug`, and `pointerVersion`; blank slugs, partial bundles, stale pointers, mismatched world/realm targets, and malformed claims are rejected before routing reuse or persistence. Game Session owns the canonical admitted-runtime normalization through `GameplayAdmissionPointerSnapshots`. `LoginCommandHandler` and `SessionRoutingNormalizationService` validate strict runtime identity while remaining scope-agnostic about `playableStateScope`; command-routing-authoritative seams such as `CommandServiceImpl` enforce scope-aware durable routing metadata. Game Logic and Entity Management receive a complete-or-absent admitted routing bundle and fail rather than consuming a partial one. Room identifiers are opaque text routing identities such as `R-*`, not positive numeric IDs. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java index 3c7e1979d8..42e9179213 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java @@ -466,8 +466,12 @@ private static synchronized EntityRuntime requireEntityRuntime() { entityPostgres.getJdbcUrl(), entityPostgres.getUsername(), entityPostgres.getPassword()); - Path migrationDirectory = - Path.of(System.getProperty("firemud.entity-management.migration-directory", "")); + String migrationProperty = + System.getProperty("firemud.entity-management.migration-directory"); + if (migrationProperty == null || migrationProperty.isBlank()) { + throw new IllegalStateException("Entity migration directory property is missing or blank"); + } + Path migrationDirectory = Path.of(migrationProperty); if (!Files.isDirectory(migrationDirectory)) { throw new IllegalStateException( "Entity migration directory is unavailable: " + migrationDirectory); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java index 7233a33fb4..a5f4e7e47a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java @@ -156,7 +156,10 @@ void loginCallsAccountServiceAndReturnsOk() throws Exception { assertThat(payloads).anyMatch(s -> s.startsWith("OK LOGIN")); assertThat(sessionContextService.findByTenantAndSessionId(42L, 1L)) .hasValueSatisfying(context -> assertThat(context.accountId()).isEqualTo(ACCOUNT_UUID)); - assertThat(redisValueStore).containsKey("accountrecentpresence:42:" + ACCOUNT_UUID); + net.firedevops.firemud.gamesession.testsupport.GameplayAsyncAssertions.assertEventually( + "account recent presence", + java.time.Duration.ofSeconds(5), + () -> redisValueStore.containsKey("accountrecentpresence:42:" + ACCOUNT_UUID)); verify(accountClient).authenticate(eq("demo@example.com"), eq("swordfish")); } From b0d2bb3b8a71c1a0464e1aab368d06618a95236e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 23:06:05 +1300 Subject: [PATCH 33/34] Apply the same bounded timestamp guard to membership and realm grants --- .../command/text/PlayCommandHandler.java | 20 +++-- .../command/text/PlayCommandHandlerTest.java | 80 ++++++++++++++++--- 2 files changed, 86 insertions(+), 14 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index ca91d17ae4..8d57edfa9e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -57,6 +57,8 @@ public class PlayCommandHandler { private static final String RESUME_DENIED_METRIC = "gamesession.session.resume_denied"; private static final String FRESH_ENTRY_FALLBACK_METRIC = "gamesession.session.fresh_entry_fallback"; + private static final Duration AUTHORITY_REPLY_MAX_FUTURE_SKEW = Duration.ofSeconds(5); + private static final Duration AUTHORITY_REPLY_MAX_AGE = Duration.ofMinutes(5); private final SessionAuthenticationService sessionAuthenticationService; private final SessionContextService sessionContextService; @@ -781,16 +783,22 @@ private boolean isSafeRealmGrantResponse( || !StringUtils.hasText(response.getEvaluatedAt())) { return false; } + return isSafeAuthorityReplyEvaluation(response.getEvaluatedAt()); + } + + private static boolean isSafeAuthorityReplyEvaluation(String evaluatedAt) { try { - Instant evaluatedAt = Instant.parse(response.getEvaluatedAt()); - Instant now = Instant.now(); - return !evaluatedAt.isAfter(now.plusSeconds(5)) - && !evaluatedAt.isBefore(now.minus(Duration.ofMinutes(5))); + return isWithinAuthorityReplyWindow(Instant.parse(evaluatedAt), Instant.now()); } catch (DateTimeParseException ex) { return false; } } + static boolean isWithinAuthorityReplyWindow(Instant evaluatedAt, Instant now) { + return !evaluatedAt.isAfter(now.plus(AUTHORITY_REPLY_MAX_FUTURE_SKEW)) + && !evaluatedAt.isBefore(now.minus(AUTHORITY_REPLY_MAX_AGE)); + } + private PlayCommandHandlingResult worldAccessDeniedFailure( SessionContext context, String tenantTag, @@ -956,7 +964,9 @@ private boolean isSafeMembershipAuthorityResponse( return false; } try { - Instant.parse(response.getEvaluatedAt()); + if (!isSafeAuthorityReplyEvaluation(response.getEvaluatedAt())) { + return false; + } if (!SessionContext.isCanonicalAccountIdentity(response.getAccountId()) || !SessionContext.isCanonicalAccountIdentity(context.accountId()) || !response.getAccountId().equals(context.accountId()) 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 8a5037e9dd..000d7536c0 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 @@ -41,6 +41,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; import org.springframework.dao.DataAccessResourceFailureException; @@ -117,7 +118,7 @@ void setUp() { .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -126,7 +127,7 @@ void setUp() { .setGameplayAvailable(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -1197,7 +1198,7 @@ void playDeniedByMembershipReturnsWorldAccessDenied() { .setMembershipExists(true) .setGameplayAdmissionAllowed(false) .setMembershipVersion(2L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1247,7 +1248,7 @@ void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { .setMembershipExists(false) .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1278,7 +1279,7 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { .setTenantId("22") .setMembershipExists(false) .setGameplayAdmissionAllowed(true) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1508,7 +1509,7 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { .setMembershipExists(false) .setGameplayAdmissionAllowed(true) .setMembershipVersion(0L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1538,7 +1539,7 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { .setMembershipExists(true) .setGameplayAdmissionAllowed(false) .setMembershipVersion(4L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1576,7 +1577,7 @@ void playWhenMembershipAuthorityAccountDoesNotExactlyMatchFailsClosed(String res .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1592,6 +1593,67 @@ void playWhenMembershipAuthorityAccountDoesNotExactlyMatchFailsClosed(String res .evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString()); } + @Test + void authorityReplyWindowIncludesExactBoundsAndRejectsOneNanosecondOutside() { + Instant now = Instant.parse("2026-10-31T00:00:00Z"); + assertThat(PlayCommandHandler.isWithinAuthorityReplyWindow(now.minusSeconds(300), now)) + .isTrue(); + assertThat(PlayCommandHandler.isWithinAuthorityReplyWindow(now.plusSeconds(5), now)).isTrue(); + assertThat( + PlayCommandHandler.isWithinAuthorityReplyWindow( + now.minusSeconds(300).minusNanos(1), now)) + .isFalse(); + assertThat( + PlayCommandHandler.isWithinAuthorityReplyWindow(now.plusSeconds(5).plusNanos(1), now)) + .isFalse(); + } + + @ParameterizedTest + @CsvSource({ + "membership,-301,false", "membership,-299,true", "membership,4,true", "membership,6,false", + "realm-grant,-301,false", "realm-grant,-299,true", "realm-grant,4,true", "realm-grant,6,false" + }) + void membershipAndRealmGrantApplyTheSameTimestampWindow( + String replyKind, long secondsFromNow, boolean accepted) { + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + String evaluatedAt = Instant.now().plusSeconds(secondsFromNow).toString(); + if (replyKind.equals("membership")) { + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId(ACCOUNT_ID) + .setTenantId("22") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(1L) + .setEvaluatedAt(evaluatedAt) + .build()); + } else { + when(accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(realmGrantResponse(true).toBuilder().setEvaluatedAt(evaluatedAt).build()); + } + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + if (accepted) { + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + } else { + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verifyNoInteractions(entityManagementClient); + } + } + @Test void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { SessionContext context = @@ -1673,7 +1735,7 @@ void playBlockedByEntitlementsReturnsBillingBlocked() { .setGameplayAvailable(false) .setEntitlementVersion(5L) .setTenantBillingSequence(5L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = From 95dfe33334a5d463d884a84665883716f7abcf07 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 31 Oct 2026 23:31:08 +1300 Subject: [PATCH 34/34] test(game-session): keep authority fixtures within freshness bounds --- .../GameSessionWebSocketHandlerIntegrationTest.java | 4 ++-- .../gamesession/command/text/SessionResumptionFlowTest.java | 6 +++--- .../command/text/TextCommandInterpreterTest.java | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 9c451a5bdf..0fce1096fc 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -272,7 +272,7 @@ void setUp() { .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(java.time.Instant.now().toString()) .build()) .when(accountClient) .getTenantMembershipForRuntime( @@ -285,7 +285,7 @@ void setUp() { .setGameplayAvailable(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(java.time.Instant.now().toString()) .build()) .when(accountClient) .getTenantEntitlementsForRuntime( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 7f8cbb5a25..da3f685796 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -175,7 +175,7 @@ void setUp() { .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(java.time.Instant.now().toString()) .build()); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -196,7 +196,7 @@ void setUp() { .setGameplayAvailable(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(java.time.Instant.now().toString()) .build()); when(entityManagementClient.listCharactersByAccount( Mockito.anyString(), @@ -472,7 +472,7 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { .setMembershipExists(true) .setGameplayAdmissionAllowed(false) .setMembershipVersion(2L) - .setEvaluatedAt("2026-03-30T00:01:00Z") + .setEvaluatedAt(java.time.Instant.now().toString()) .build()); TextCommandInterpretationResult secondLogin = interpreter.interpret("1", LOGIN_PAYLOAD, false); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 9a2b99d9f8..7fc3bb6793 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -177,7 +177,7 @@ void setUp() { .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(java.time.Instant.now().toString()) .build()); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -198,7 +198,7 @@ void setUp() { .setGameplayAvailable(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(java.time.Instant.now().toString()) .build()); when(gameLogicClient.queryInventory(Mockito.any(SessionContext.class))) .thenReturn(