diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 46f2e83d93..818fef7121 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -90,15 +90,17 @@ 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. Ordinary control-UI/gameplay login results, tenant IDs, and membership identities retain their current numeric contracts. 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 -[ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) owns durable public UUID identity; this section owns its bounded Account API consequences. Registration `AccountDto.id` / `CreateAccountResponse.account_id`, every explicit public-production JOIN outcome, profile GET/UPDATE and gRPC JSON projections, and the Account and nested-profile components of both existing Account-local export envelopes carry the exact persisted canonical non-nil Account UUID. Account projection verifies UUID provenance and the private source-row binding. JOIN and profile projection additionally require reverse owner readback; profile projection validates tenant/owner coherence and rereads the full Account because its repository embeds only a partial owner. Unavailable or inconsistent owner evidence returns `AUTH_UNAVAILABLE`, never a numeric or nil substitute. JOIN projection follows transaction completion, so projection failure cannot rewrite committed membership, receipts, audit or replay evidence. Private scope/operation/member keys and immutable digests retain their existing representation. +[ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) owns durable public UUID identity; this section owns its bounded Account API consequences. Registration `AccountDto.id` / `CreateAccountResponse.account_id`, ordinary authentication and player-bootstrap Account results, every explicit public-production JOIN outcome, profile GET/UPDATE and gRPC JSON projections, and the Account and nested-profile components of both existing Account-local export envelopes carry the exact persisted canonical non-nil Account UUID. Account projection verifies UUID provenance and the private source-row binding. JOIN and profile projection additionally require reverse owner readback; profile projection validates tenant/owner coherence and rereads the full Account because its repository embeds only a partial owner. Unavailable or inconsistent owner evidence returns `AUTH_UNAVAILABLE`, never a numeric or nil substitute. JOIN projection follows transaction completion, so projection failure cannot rewrite committed membership, receipts, audit or replay evidence. Private scope/operation/member keys and immutable digests retain their existing representation. -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 verifies persisted provenance and source-row ownership through `resolveAccountStorageId(UUID)` before private row keys reach persistence. Profile caller checks precede owner resolution; profile service methods retain private numeric row access, while the update request carries the UUID to the Account owner for its own resolution. The global Account handlers resolve selectors before passing private numeric keys to their existing 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 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. -Ordinary control-UI/gameplay issuance still produces numeric subjects and Account claims, but shared non-internal JWT intake and forwarding now require canonical UUID identity and refuse those numeric tokens. Tenant identifiers and current authorization remain unchanged. Profile REST selectors and the `GetProfile`/`UpdateProfile` gRPC selectors are the bounded exception: they require a canonical Account UUID, bind it to the exact caller UUID subject, and resolve the private row only after that caller check. Controlled UUID callers exercise the prepared profile boundary; ordinary numeric issuer credentials are refused at shared intake, so this preparation does not activate profile access for ordinary sessions or change runtime membership identities. 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). +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 @@ -116,6 +118,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. +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. - `SendNotification` – deliver account notifications asynchronously. @@ -128,11 +132,11 @@ The unregistered canonical `Authenticate` receiver requires the exact same-names - `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 and profile UUID selectors follow [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity); other gRPC request selectors retain their method-specific contracts. +- Account-owned response identity and profile UUID selectors follow [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. -- `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. @@ -254,6 +258,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 | @@ -303,9 +309,11 @@ 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 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). -The legacy `GET /profiles/{accountId}?tenantId=...` and `PUT /profiles/{accountId}` handlers follow [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity), including canonical UUID selectors and PUT path/body equality. They bind the selector to the exact caller UUID subject before Account resolves the private row, then retain current tenant-membership checks (`gameplayAdmissionAllowed` is not required) and post-commit update notification. Ordinary numeric issuer credentials are refused by shared intake before these handlers; controlled UUID-caller proof does not establish genuine ordinary UUID issuance. Legacy PUT rejects `HIDDEN_STAFF` before persistence; a successful update stores the supplied selectable policy. Normalizing retained legacy policy to `PRIVATE` applies to read/export projection without rewriting that row, not acceptance of the retired policy on update. These selectors do not authorize another Account's profile or activate the canonical tenant-qualified route, scoped tenant roles, or membership-authority-generation checks. The legacy route and its route/policy shape remain implementation drift. +The legacy `GET /profiles/{accountId}?tenantId=...` and `PUT /profiles/{accountId}` handlers follow [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity), including PUT path/body equality. They enforce exact UUID `SessionContext` self-binding before private owner resolution, retaining current tenant-membership checks (`gameplayAdmissionAllowed` is not required), public policy vocabulary checks, and post-commit update notification. Legacy PUT rejects `HIDDEN_STAFF` before persistence; a successful update stores the supplied selectable policy. Normalizing retained legacy policy to `PRIVATE` applies to read/export projection without rewriting that row, not acceptance of the retired policy on update. These selectors do not authorize another Account's profile or activate the canonical tenant-qualified route, scoped tenant roles, or membership-authority-generation checks. The legacy route and its route/policy shape remain implementation drift. 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. @@ -313,7 +321,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. -The following ordinary login example retains its numeric identity contract; UUID response projections follow [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). +The following ordinary login example uses the receiving UUID identity contract; response projections follow [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). Canonical current `/auth/login` success shape: @@ -321,7 +329,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 6ed8ab05b7..cd41e4b505 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; response projection rereads the full owner and supplies its verified UUID to the generated mapper, including both existing export paths. 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). +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. This Account-local preparation leaves ordinary control-UI/gameplay authentication numeric; the bootstrap profile identity transition is recorded in the linked tracker. 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. Private numeric row keys remain local to those storage calls; the [Account API contract](./api-contracts.md#rest-apis) owns caller authorization, 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. Private numeric row keys remain local to storage; the [Account API contract](./api-contracts.md#rest-apis) owns caller authorization, selector, and failure behavior. The final receiving composition carries UUID identity through shared context, gRPC and Logging consumers; tenant storage selectors retain their numeric representation. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving) records current implementation and focused proof. Full token-profile qualification and production authorization custody remain separate. 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. Tenant IDs and ordinary control-UI/gameplay authentication results and JWT subjects/claims remain numeric at this preparation boundary; shared non-internal consumers already require UUID caller identity and refuse numeric credentials; the player-bootstrap credential/result and derived-scope UUID profiles are described above. Profile response `accountId` and profile REST and Social & Groups-facing gRPC selectors use the Account UUID while profile persistence remains keyed by Account's private numeric row. Profile handlers bind that UUID to the caller subject before resolving the Account row; the gRPC profile and presence-policy handlers also require the exact same-namespace Social & Groups workload. Current ordinary authentication still issues numeric subjects that shared intake refuses before owner handlers; controlled UUID callers exercise the prepared checks. Runtime membership request/response identities remain numeric. 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. Shared non-internal intake and forwarding now require UUID caller identity and refuse the numeric ordinary credentials. `GrpcClientAuth`, Logging & Admin actor readers, Automation ingress and Social authorization consume strict UUID context; legacy numeric GameInstance owner/StartSession comparisons remain separate unqualified drift and never infer UUID-to-private-row identity. Controlled UUID-caller proof does not establish genuine ordinary UUID issuance or the final gameplay/moderation/Entity composition. Focused native repository, retained-row migration and Account HTTP proof is recorded in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md); [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. @@ -66,7 +66,7 @@ Account implements bounded owner-local cleanup of expired password-reset, email- Account also performs a bounded sweep of public connect-scope evidence after its configured scope expiry. It deletes only rows with a valid parsed expiry at or before the captured UTC time and no `account_join_operations` reference of any status; malformed expiry rows remain untouched without blocking valid rows. V27 adds a restrictive foreign key from each JOIN operation to its exact scope row, fencing concurrent intent insertion against deletion. The sweep does not expire JOIN operation receipts or change account-deletion retention. -The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback applies the terminal retry checks when a terminal row is present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. An exact retry of a terminal JOIN replays its stored result only after the retained scope is still unexpired and current target/entitlement authority is available and matches the stored policy digest; expiry, unavailable authority, or changed policy fails closed without rewriting the terminal operation or membership. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. +The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback applies the terminal retry checks when a terminal row is present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. An exact retry of a terminal JOIN replays its stored result only after the retained scope is still unexpired and current target/entitlement authority is available and matches the stored policy digest; expiry, unavailable authority, or changed policy fails closed without rewriting the terminal operation or membership. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; focused native PostgreSQL and HTTP execution is recorded with its source-specific limits in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md). No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. Account has source-only persistence for individual Creator Party identity, hosted-terms acceptance/environment-binding evidence, and (from V98) disclosure handoffs with immutable captured source evidence. The V98 database guards constrain handoff identity, result transitions, and source-evidence insertion. A passive Account source-fence seam now excludes unsettled World participation from applicable source mutation/abort settlement and hosted-terms disclosure preparation/dispatch admission; `HostedTermsDisclosureHandoff` and its repository use the existing V98 journal. The unregistered historical World-participation reader resolves retained participation coordinates from the complete unchanged original tuple, verifies the retained capture and source-child vector, and can read after lease expiry or immutable terminal settlement; it uses existing rows and introduces no migration or table. It does not establish currentness, renew or admit authorization, or classify an Account expiry or failed response as World `ABORTED`; only the World owner can produce that terminal outcome with its original commit/fence evidence. The handoff retains opaque authority evidence as supplied and does not authenticate it. No verifier, dispatcher, transport, registry/runtime binding, creator UI, or Game Design evidence binding is registered. Reserve, claim, and publication paths that require the hosted-terms workflow remain unavailable. The acceptance/currentness authority remains target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md), with changed-terms continuity under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner workflow is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled. @@ -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). The player-bootstrap credential/result uses that UUID; ordinary control-UI/gameplay authentication and other downstream session carriers remain separate migration work. +- `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/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 274e8ad1dc..0db89021b6 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -6,9 +6,9 @@ The authoritative REST schema source lives in [../../../../services/entity-manag ## 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 retains actual Account ownership in `characters.account_uuid`; numeric `characters.account_id` remains private source-row evidence. Neither field derives or reconstructs the other. +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. -Account UUID ownership alone does not establish canonical tenant, namespace, actor assignment, `OWNER_RESOLVED`, created-origin, admission or activation authority. Existing provenance predicates and registration holds remain in force. Implementation and remaining wire/seed convergence belong to the [Entity tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#ordinary-account-uuid-ownership). +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 @@ -18,13 +18,13 @@ 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. 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. @@ -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/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 351f04fbc0..f64797775a 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -4,7 +4,8 @@ This document defines Entity Management’s runtime model, persistence ownership ## Implementation Status -Ordinary Account UUID storage and nested-character copy carriers are prepared separately from wire activation. V1024 permits UUID-owned ordinary rows without fabricated numeric evidence while preserving retained rows and canonical created-actor/provenance guards. Existing numeric ordinary services and demo seeding remain unchanged until final receiving activation; the prepared mTLS authentication client is not yet invoked by that seeder. Representation belongs to [API Contracts](./api-contracts.md#ordinary-account-ownership); detailed capability and proof status belong to the [Entity tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#ordinary-account-uuid-ownership). +- 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. @@ -23,7 +24,7 @@ Ordinary Account UUID storage and nested-character copy carriers are prepared se - 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/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index 185f6c15ec..7f13582658 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) | | | @@ -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/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 3b1d9b0907..7327993634 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. Focused public copy-carrier owner-isolation coverage is added in [OrdinaryAccountUuidCopyCarrierTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/OrdinaryAccountUuidCopyCarrierTest.java); R1311 passes the three carrier cases with no failures, errors, or skips. 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); [OrdinaryAccountUuidCopyCarrierTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/OrdinaryAccountUuidCopyCarrierTest.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. Strict ordinary UUID wire/service/DTO/seed activation and Account-authenticated fresh-image smoke remain pending under #2972; see [Player Access](./player-access-and-session.md#account-and-entity-owner-uuid-preparation). 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 isolation. Focused public copy-carrier owner-isolation coverage is added in [OrdinaryAccountUuidCopyCarrierTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/OrdinaryAccountUuidCopyCarrierTest.java); R1311 passes the three carrier cases with no failures, errors, or skips. 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); [OrdinaryAccountUuidCopyCarrierTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/OrdinaryAccountUuidCopyCarrierTest.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. | @@ -249,9 +249,9 @@ The next review correction at code checkpoint `ce02d51f608f199e531de32c1d15f63cb ### Ordinary Account UUID ownership -The prepared storage boundary preserves actual Account UUID ownership through character persistence, nested copies and the UUID roster reader, while retaining the numeric ordinary service/DTO/selector path until activation. Forward V1024 permits fresh UUID-owned ordinary rows with unresolved canonical provenance and preserves existing numeric rows, source evidence and created-actor guards. A demo-only mTLS authentication client is prepared but is not yet connected to the existing numeric seeder. The [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#ordinary-account-ownership) owns representation and authority. +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. -Complete Entity qualification passes 461 unit and 135 native PostgreSQL cases with no failures, errors or skips, including upgrade/row/history preservation, exact UUID owner/tenant isolation and unchanged provenance/creation denials. Account qualification separately passes 1,727 unit cases with four existing assumption-skips and eight native HTTP cases, with enabled affected analysis, generation, formatting and documentation passing. R1280 freshly proved the retained numeric issuer/Entity service/demo-seed baseline on a fresh image through direct backend WebSocket WORLDS/LOGIN/PLAY/LOOK/LOGOUT; public-edge holds, authenticated cleanup and proof limits are recorded in [Player Access](./player-access-and-session.md#account-and-entity-owner-uuid-preparation). #2972 still owns final strict wire/service/DTO/seed activation and real Account-authenticated fresh-image smoke; UUID storage alone is not receiver completion, canonical actor promotion, registration or admission. +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. The focused [Ordinary Account UUID copy-carrier test](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/OrdinaryAccountUuidCopyCarrierTest.java) covers the public `setCharacter`/`getCharacter` defensive-copy contracts of `CharacterEquipmentEntry`, `ContainerInstance`, and `InventoryEntry`: exact persisted UUIDs remain distinct when owners share the same private numeric source ID; mutations to setter inputs or getter results do not alter carrier state; and null or unresolved UUID ownership stays absent without being derived from numeric `accountId`. R1311 passed all three cases locally at its attributed source; current published-head CI remains a separate pending obligation. This unit scope does not establish PostgreSQL owner readback or runtime activation. 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 f9b4823463..e87f53a531 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. | @@ -482,61 +482,71 @@ Live Account authentication hashes and verifies passwords with `argon2-jvm` Argo #### Ordinary Account authentication owner preparation -Local receiving preparation 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. This adds no Account UUID storage, mapping subsystem, schema, wire/profile transition, or downstream activation. Ordinary authentication results and JWT Account claims remain numeric at this preparation boundary, but shared non-internal intake rejects those numeric tokens before protected HTTP/gRPC handlers. Player-bootstrap credentials and connect-scope artifacts use their separately qualified UUID profiles; final ordinary issuer convergence belongs to #2972. +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 Account service and native application proof covers persisted owner/provenance/readback refusal before signing, challenge consumption or session writes. Current ordinary response/JWT assertions remain numeric; protected HTTP selector proof separately expects numeric-token refusal and uses controlled UUID-claim callers for authorized paths. Historical run counts and recovery attribution remain in the review records. Full final ordinary issuer/shared-consumer composition remains #2972 work; canonical registry/custody/admission and activation holds remain unchanged. +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 -Local source 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. +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 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 JWT issuance remains numeric until #2972. Shared forwarding/intake and [prepared Social consumers](#social-uuid-receiver-preparation) already require canonical UUID callers and refuse those numeric ordinary tokens; the dedicated bootstrap proof does not qualify that final issuer-to-consumer boundary. Public admission and gameplay activation remain held. +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 UUID receiver preparation](#social-uuid-receiver-preparation), public admission and gameplay activation remain outside this bootstrap-only transition. #### Bootstrap-connect-scope UUID artifact -Local source migrates the existing opaque `bootstrap-connect-scope` artifact's signed subject and Account claim to canonical persisted Account UUID text. Browser discovery and the implemented direct-text Account RPC converge through one mint/retain boundary, with existing Account-owner readback before signing or retaining scope evidence. The dedicated reader rejects numeric, nil, noncanonical or contradictory identity before translating through Account-owned UUID lookup; owner unavailability remains `AUTH_UNAVAILABLE`, separate from `CONNECT_SCOPE_INVALID`. Current caller/target/route/pointer/catalog/expiry checks, private numeric retained-scope/JOIN rows, v1 digest/replay/race guards and the unavailable connect-token issuer remain in place. No schema, guessed mapping, dual-format parser, ordinary JWT issuance, shared session intake/forwarding or Social authorization change is introduced. +The published #3352 scope boundary migrates the existing opaque `bootstrap-connect-scope` artifact's signed subject and Account claim to canonical persisted Account UUID text. Browser discovery and the implemented direct-text Account RPC converge through one mint/retain boundary, with existing Account-owner readback before signing or retaining scope evidence. The dedicated reader rejects numeric, nil, noncanonical or contradictory identity before translating through Account-owned UUID lookup; owner unavailability remains `AUTH_UNAVAILABLE`, separate from `CONNECT_SCOPE_INVALID`. Current caller/target/route/pointer/catalog/expiry checks, private numeric retained-scope/JOIN rows, v1 digest/replay/race guards and the unavailable connect-token issuer remain in place. No schema, guessed mapping, dual-format parser, ordinary JWT issuance, shared session intake/forwarding or Social authorization change is introduced. 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. 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 and physical PostgreSQL proof covers UUID response projection, generated mapping, retained private rows, replay and owner-readback refusal. Current prepared HTTP proof uses test-owned UUID-claim callers through the canonical main policy/interceptor; numeric ordinary Account-issued tokens are refused at shared intake. Earlier ordinary-numeric credential access results belong to their original source comparisons in the review records. These component fixtures do not qualify production PKI/namespace, final ordinary issuance, canonical registry or public gameplay admission. +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. #### Account REST profile UUID selectors -The legacy profile GET/PUT handlers implement the [Account UUID response and REST selector contract](../../architecture/microservices/account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity) through `ProfileController`, `AccountRequestReaders` and Account's persisted-owner resolver. Exact caller UUID binding precedes private owner lookup; current membership checks, reserved-policy refusal and post-commit notification remain. The ordinary issuer is still numeric, so its tokens cannot pass shared intake for these routes until #2972; no numeric self-binding is supplied here. +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. + +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 + +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. -Controller and native HTTP proof uses controlled UUID-claim callers to cover successful GET/PUT, malformed/numeric/nil selectors, path/body mismatch, wrong-owner or missing-membership refusal and reserved-policy denial while preserving the private profile row. Unit evidence separately covers inconsistent/unavailable owner mapping to `AUTH_UNAVAILABLE`; the V29 persisted-identity trigger prevents the native fixture from rewriting owner evidence. Original R1202 and preceding numeric-token results retain their historical attribution in the review records and are not current issuer-to-HTTP qualification. Canonical tenant-qualified profile routes/authorization, full registry/custody and gameplay activation remain held. +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. + +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. #### Account-owned global REST UUID selectors -The five AccountController selector handlers—login-auth-mode GET/PUT, Account export, tenant export and DELETE—implement the [Account UUID response and REST selector contract](../../architecture/microservices/account-service/api-contracts.md#account-uuid-response-and-rest-selector-identity). Caller UUID/global-role checks precede private owner lookup; existing tenant-export access, unavailable factor-update and deletion-retention denials remain. Ordinary control-UI issuance stays numeric, and those tokens are refused at shared intake before these handlers; final ordinary issuance belongs to #2972. +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. -Controller and native main-configuration HTTP proof uses test-owned UUID claims for self/global-role/tenant branches, validates UUID projection and retained Account/profile rows, and rejects numeric/malformed/nil/uppercase selectors before dispatch. Inconsistent or unavailable owner resolution remains `AUTH_UNAVAILABLE`; factor update remains `501`, and JOIN receipt, billing and child-retention deletion denials remain intact. Earlier R1205/R1206 counts and numeric ordinary-credential claims cover their original source comparisons only. This bounded selector proof does not qualify final Account-issued UUID credentials, canonical tenant-wide/asynchronous export, token registry, production custody or gameplay activation. +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 Account owns canonical identity and owner resolution; Social consumes that identity. The Social receiver, storage, temporary producer incompatibility, restoration and focused proof status belong to [Communication, Social, and Presence](./player-experience-commands-and-communication.md#communication-social-and-presence). Ordinary issuer/shared-context convergence and the held production, registration, admission and activation boundaries remain in this Access tracker. -#### UUID consumer preparation - -Strict UUID intake/forwarding, shared Social/Logging/Automation context readers, caller binding before Account REST owner lookup, and Game Session communication/presence consumers are implemented. Durable communication rejection retains player error output through delivery and replay. Ordinary Account issuance, gameplay signed-actor verification, PLAY moderation and Entity roster producers remain numeric. Shared non-internal JWT intake rejects every numeric ordinary token before protected HTTP/gRPC handlers, including Account routes; this is broader than refusal inside individual consumer operations. Generic credential transport LOGIN/PLAY uses its separate current producer baseline. Final ordinary UUID issuance and supported receiving restoration belong to #2972; no numeric fallback, data rewriting or authority relaxation is supplied. UUID-only presence writers retain no presence for those preparation callers. - -Focused proof covers the complete 2,806-case Game Session unit suite, selected Account/Social native storage, controlled Game Session/TCP transport and two physical World mTLS cases. The current preparation fixture correction passes 41 native HTTP/login/WebSocket/retirement cases with enabled affected analysis and formatting. Separate run attribution, failed aggregates and retained XML belong to the review records. 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. Production custody, registry/profile qualification, default registration, gameplay admission and activation remain unqualified. +#### Ordinary UUID issuer and receiving -Tracked restoration gap: #2972 owns the preserved final UUID issuer, Profile/internal DTO and native Account postimages, together with UUID-positive transport/item/communication/load proof. Its final Login and WebSocket fixtures must restore positive UUID live/recent presence and AFK/reconnect coverage. Legacy numeric GameInstance owner/StartSession authorization still uses the common numeric owner helper and remains separate unqualified drift; UUID callers are never mapped to those private numeric owner rows. Authorized tenant access remains independently checked on instance reads/control. The temporary numeric preparation fixtures prove refusal and ordinary replay/context behavior only. 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. -#### Account and Entity owner UUID preparation +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. -The adjacent owner boundary prepares Account profile UUID request/owner resolution and exact runtime-reader workload authorization without changing the ordinary numeric credential issuer or runtime membership identities. Shared non-internal intake still refuses numeric ordinary JWTs; controlled UUID callers exercise the prepared profile boundary. Entity stores/copies actual Account UUID ownership and exposes the internal UUID repository reader while retaining its numeric wire/service/demo-seed baseline. Its ordinary UUID seeding client is not yet invoked. The [Entity tracker](./gameplay-rules-entities-and-effects.md#ordinary-account-uuid-ownership) records storage and retained-row guard proof limits. +R1343 and receiving R1347 qualify the real Account HTTP bootstrap-to-Entity component path: Account registration, bootstrap JWT and scope validation carry the persisted UUID over actual mTLS to Entity service/repository and PostgreSQL, with cross-owner/tenant denials and retained numeric-owner rows unchanged. The focused integration case passes without skips with enabled analysis and formatting. Game Session realm/pointer/membership responses and test PKI remain controlled; ordinary Entity rows stay quarantined without canonical tenant/namespace promotion. This closes the missing HTTP-to-Entity composition proof, while genuine World admission, production custody and current full remote CI remain unproved. -Complete affected Account unit/native HTTP and Entity storage/copy qualification passes with enabled generation, analysis, formatting and documentation; the Entity tracker retains exact counts and four Account assumption-skip limits. R1280 freshly proved the fresh-image numeric gameplay baseline through a separate direct backend WebSocket smoke: WORLDS, LOGIN, PLAY, LOOK and LOGOUT passed on the retained numeric issuer/Entity service/demo-seed path. Public-edge admission remained held: Gateway and TCP Proxy readiness were OUT_OF_SERVICE, Telnet startup was unavailable, and the in-container first-party Gateway loopback handshake was denied because replay protection was unavailable; host-published ingress was not exercised. Authenticated default cleanup removed the run-owned Compose containers, network and volumes, and the independent exact-project check found no remaining resources. The UUID seeding client was not invoked, so final #2972 activation of the UUID issuer, gameplay/moderation consumers, Entity wire/services and Account-authenticated seeding remains pending; complete source and positive UUID proof postimages remain preserved there. This preparation grants no registration, canonical actor promotion or admission authority. +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. #### Presence-owner correlation prerequisite @@ -558,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/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..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 @@ -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/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 4f6d893740..45200b4482 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -88,6 +88,9 @@ 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"))) } @@ -109,6 +112,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) @@ -146,10 +165,16 @@ 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 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/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/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/repository/AccountRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java index 4d9769a331..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 @@ -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; @@ -15,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; @@ -22,6 +25,7 @@ @Repository public class AccountRepository { + private static final Logger logger = LoggerFactory.getLogger(AccountRepository.class); private final DSLContext dsl; private final AccountAuthoritySourceEvidenceRepository sourceEvidence; @@ -112,6 +116,34 @@ 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) { + logger.warn( + "Omitting Account UUID batch row rejected by scalar readback; exceptionClass={}", + ex.getClass().getSimpleName()); + } + } + 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 94cf793a9d..ab7e57ddf6 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; @@ -60,7 +61,9 @@ 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 org.springframework.transaction.TransactionException; import tools.jackson.core.JacksonException; import tools.jackson.databind.JsonNode; import tools.jackson.databind.json.JsonMapper; @@ -110,17 +113,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, @@ -163,19 +168,23 @@ 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 (!request.getPlayerContext().getAccountId().equals(result.accountId()) + || result.tenantId() != caller.tenantId()) { + throw new IllegalStateException("Account JOIN result does not match the validated caller"); + } response .setSuccess(result.success()) .setOutcomeCode(result.outcomeCode()) @@ -252,15 +261,28 @@ private static UUID requireCanonicalAccountUuid(String value) { 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) { @@ -359,7 +381,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(); @@ -384,6 +406,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(); } } @@ -413,7 +442,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( @@ -442,6 +471,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(); } @@ -453,14 +489,21 @@ public void getTenantMembershipForRuntime( 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()) @@ -472,12 +515,11 @@ public void getTenantMembershipForRuntime( responseObserver.onNext(response); responseObserver.onCompleted(); } catch (AdminAuthorizationException ex) { - GetTenantMembershipForRuntimeResponse response = + responseObserver.onNext( GetTenantMembershipForRuntimeResponse.newBuilder() .setError( appError("GetTenantMembershipForRuntime", "PERMISSION_DENIED", ex.getMessage())) - .build(); - responseObserver.onNext(response); + .build()); responseObserver.onCompleted(); } catch (InvalidRequestException ex) { GetTenantMembershipForRuntimeResponse response = @@ -494,6 +536,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(); } } @@ -504,19 +556,34 @@ public void getRealmAccessGrantForRuntime( 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()) @@ -524,12 +591,11 @@ public void getRealmAccessGrantForRuntime( responseObserver.onNext(response); responseObserver.onCompleted(); } catch (AdminAuthorizationException ex) { - GetRealmAccessGrantForRuntimeResponse response = + responseObserver.onNext( GetRealmAccessGrantForRuntimeResponse.newBuilder() .setError( appError("GetRealmAccessGrantForRuntime", "PERMISSION_DENIED", ex.getMessage())) - .build(); - responseObserver.onNext(response); + .build()); responseObserver.onCompleted(); } catch (InvalidRequestException ex) { GetRealmAccessGrantForRuntimeResponse response = @@ -546,6 +612,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(); } } @@ -556,9 +632,9 @@ public void getTenantEntitlementsForRuntime( StreamObserver responseObserver) { try { requireRuntimeEntitlementsPeer(); - var dto = - accountService.getTenantEntitlementsForRuntime( - requirePositiveRequestId(request.getTenantId(), "tenantId"), request.getRequestId()); + 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())) @@ -673,22 +749,60 @@ public void listPresenceVisibilityPolicies( throw new InvalidRequestException( "accountIds must contain at most " + MAX_ACCOUNT_IDS_PER_REQUEST + " entries", null); } - java.util.List accountIds = + java.util.List accountUuids = request.getAccountIdsList().stream() - .map(accountId -> requirePositiveRequestId(accountId, "accountId")) + .map(AccountGrpcService::requireCanonicalAccountUuid) .distinct() .toList(); + 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 (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; + } + UUID previousAccountUuid = accountUuidsByStorageId.putIfAbsent(storageId, accountUuid); + if (previousAccountUuid != null && !previousAccountUuid.equals(accountUuid)) { + throw new IllegalStateException("Account UUID resolution returned an ambiguous row"); + } + } + 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 = + 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) { @@ -714,7 +828,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(); } @@ -820,7 +938,7 @@ public void exportAccount( try { var data = accountService.exportAccountData( - requirePositiveRequestId(request.getAccountId(), "accountId")); + resolveAccountStorageIdForRpc(requireCanonicalAccountUuid(request.getAccountId()))); ExportAccountResponse response = ExportAccountResponse.newBuilder() .setAccountJson(JsonMapper.builder().build().writeValueAsString(data.account())) @@ -828,6 +946,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() @@ -860,7 +985,7 @@ public void exportTenantData( var data = accountService.exportTenantData( requirePositiveRequestId(request.getTenantId(), "tenantId"), - requirePositiveRequestId(request.getAccountId(), "accountId")); + resolveAccountStorageIdForRpc(requireCanonicalAccountUuid(request.getAccountId()))); ExportTenantDataResponse response = ExportTenantDataResponse.newBuilder() .setTenantId(String.valueOf(data.tenantId())) @@ -872,6 +997,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() @@ -902,10 +1034,19 @@ public void deleteAccount( DeleteAccountRequest request, StreamObserver responseObserver) { try { AdminRoleGuard.requireAdminRole(); - accountService.deleteAccount(requirePositiveRequestId(request.getAccountId(), "accountId")); + accountService.deleteAccount( + 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() @@ -1013,7 +1154,7 @@ public void linkExternalAccount( accountService.linkExternalAccount( new net.firedevops.firemud.accountservice.dto.LinkExternalAccountRequest( requirePositiveRequestId(request.getTenantId(), "tenantId"), - requirePositiveRequestId(request.getAccountId(), "accountId"), + resolveAccountStorageIdForRpc(requireCanonicalAccountUuid(request.getAccountId())), request.getProvider(), request.getExternalId())); var response = @@ -1022,6 +1163,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() @@ -1049,13 +1198,21 @@ public void requestEmailVerification( responseObserver) { try { accountService.requestEmailVerification( - requirePositiveRequestId(request.getAccountId(), "accountId")); + 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() @@ -1116,6 +1273,29 @@ 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 | 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( String operation, String code, String message) { return meterRegistry == null 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 debb161fc8..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; @@ -299,17 +300,16 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult authentica String username, String password) { PrimaryAuthentication authentication = authenticateAccountIdentity(username, password, true); Account account = authentication.account(); - requireAuthenticationAccountOwner(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 @@ -324,17 +324,16 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult authentica PrimaryAuthentication authentication = authenticateAccountIdentity(gameplayAccount, password, true); Account account = authentication.account(); - requireAuthenticationAccountOwner(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 @@ -399,17 +398,16 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult verifyEmai throw invalidCredentials(); } requireAuthenticationEligible(account); - requireAuthenticationAccountOwner(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 @@ -419,8 +417,7 @@ public PlayerBootstrapResult issuePlayerBootstrap(String accountIdentifier, Stri PrimaryAuthentication authentication = authenticateAccountIdentity(accountIdentifier, secret, true); Account account = authentication.account(); - requireAuthenticationAccountOwner(account); - String accountUuid = account.getAccountUuid().toString(); + String accountUuid = requireAuthenticationAccountUuid(account).toString(); authentication.emailLoginChallenge().ifPresent(accountEmailLoginChallengeRepository::delete); String jti = UUID.randomUUID().toString(); long issuedAt = System.currentTimeMillis(); @@ -518,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( @@ -601,7 +599,7 @@ public DirectTextJoinScope issueDirectTextConnectScope( } Instant evaluatedAt = Instant.now(); Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); - requireAuthenticationAccountOwner(account); + requireAuthenticationAccountUuid(account); String scopeId = mintAndRetainConnectScope( new BootstrapContext(caller.accountId(), account.getAccountUuid()), @@ -984,8 +982,7 @@ private String responseAccountUuid(Account account, Long accountId) { if (!Objects.equals(accountId, account.getId())) { throw new IllegalStateException("Account response readback returned a different owner"); } - requireAuthenticationAccountOwner(account); - return account.getAccountUuid().toString(); + return requireAuthenticationAccountUuid(account).toString(); } catch (RuntimeException ex) { throw new AuthenticationException( "AUTH_UNAVAILABLE", "Account response authority is unavailable", ex); @@ -2111,14 +2108,15 @@ private Account requireAccount(Long accountId) { .orElseThrow(() -> new IllegalArgumentException("Account not found")); } - /** Requires the authenticated identity to resolve back to its exact persisted Account owner. */ - private void requireAuthenticationAccountOwner(Account account) { + private UUID requireAuthenticationAccountUuid(Account account) { try { requireAuthenticationPersistedIdentity(account); - Long storageId = resolveAccountStorageId(account.getAccountUuid()); + 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"); } + return accountUuid; } catch (IllegalArgumentException | IllegalStateException | DataAccessException ex) { logger.warn( "Account owner validation failed during issuance; cause={}", @@ -2138,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 @@ -2174,7 +2220,7 @@ private Map authenticationTokenClaims(String audience, Account a "aud", audience, "accountId", - account.getId(), + account.getAccountUuid().toString(), "globalRoles", globalRoles, "jti", diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 0fef592ec8..d0b963a010 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -128,16 +128,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: string format: uuid - description: Canonical lowercase non-nil persisted Account UUID. + description: Canonical lowercase non-nil persisted Account UUID; never the private numeric database primary key. bootstrapToken: type: string issuedAt: 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 4dfe5bcb74..0cf8542d4b 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 @@ -77,6 +77,11 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private HttpAuthProperties httpAuthProperties; @Autowired private ObjectProvider httpJwtAuthInterceptorProvider; + @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; @@ -175,9 +180,8 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws } @Test - void - bootstrapUsesPersistedUuidAcrossPasswordOtpReadsAndInvalidationWhileOrdinaryLoginStaysNumeric() - throws Exception { + void ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity() + throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); String username = "auth-uuid-" + suffix; String email = username + "@example.com"; @@ -232,12 +236,22 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws assertThat(authenticationResponse.statusCode()).isEqualTo(200); var data = jsonMapper.readTree(authenticationResponse.body()).path("data"); - assertThat(data.path("accountId").asLong()).isEqualTo(numericAccountId); + 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(Long.toString(numericAccountId)); - assertThat(((Number) claims.get("accountId")).longValue()).isEqualTo(numericAccountId); + assertThat(claims.getSubject()).isEqualTo(persistedAccountUuid.toString()); + assertThat(claims.get("accountId", String.class)).isEqualTo(persistedAccountUuid.toString()); + 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")) @@ -326,6 +340,56 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws 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) .fetchOne(0, UUID.class)) @@ -341,11 +405,39 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws "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 browserAndControlledDirectScopesRetainUuidClaimsAndPrivateJoinRowsWithPreparedHttpCaller() - throws Exception { + void browserAndControlledDirectScopesRetainUuidClaimsAndPrivateJoinRows() throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); String username = "scope-" + suffix; var account = @@ -410,7 +502,7 @@ void browserAndControlledDirectScopesRetainUuidClaimsAndPrivateJoinRowsWithPrepa .connectScopeId(); var player = net.firedevops.firemud.shared.v1.PlayerExecutionContext.newBuilder() - .setAccountId(Long.toString(row)) + .setAccountId(account.id()) .setTenantId(Long.toString(tenant)) .setRealmId(realm) .setPlayableStateNamespaceId(namespace) @@ -571,15 +663,8 @@ public void onCompleted() {} assertThat(httpAuthProperties.getRoleRequirement()) .isEqualTo(HttpAuthRoleRequirement.AUTHENTICATED); assertThat(httpJwtAuthInterceptorProvider.getIfAvailable()).isNotNull(); - String numericProducer = accountService.authenticate(username, "password123").authToken(); + String ordinary = accountService.authenticate(username, "password123").authToken(); String accountUuid = account.id(); - String ordinary = - controlledUuidCallerAfterNumericProducerRefusal( - numericProducer, - accountUuid, - "/profiles/" + accountUuid + "?tenantId=" + tenant, - "/profiles/" + accountUuid, - profileUpdateBody(tenant, accountUuid, "refused numeric producer")); HttpResponse profileResponse = HTTP_CLIENT.send( HttpRequest.newBuilder( @@ -780,6 +865,132 @@ public void onCompleted() {} 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")) @@ -810,17 +1021,15 @@ private void invalidateBootstrapSession(long accountId, String token) throws Exc @Test void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws Exception { + String accountUuid = java.util.UUID.randomUUID().toString(); String token = jwtUtil.generateToken( - "f22f310d-5464-45f0-9dc4-c37353004403", + accountUuid, java.util.Map.of( - "accountId", - "f22f310d-5464-45f0-9dc4-c37353004403", - "globalRoles", - java.util.List.of("platformAdmin"))); + "accountId", accountUuid, "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(); @@ -834,7 +1043,7 @@ void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws } @Test - void preparedAccountSelectorsRejectNumericProducerAndPreserveAuthorizationAndDenials() + void accountSelectorRoutesUsePersistedUuidAndPreserveCurrentAuthorizationAndDenials() throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); String username = "account-selector-" + suffix; @@ -870,15 +1079,8 @@ void preparedAccountSelectorsRejectNumericProducerAndPreserveAuthorizationAndDen "Account selector profile", "retained during denied deletion"); - String numericProducer = accountService.authenticate(username, "password123").authToken(); + String ordinary = accountService.authenticate(username, "password123").authToken(); String accountUuid = account.id(); - String ordinary = - controlledUuidCallerAfterNumericProducerRefusal( - numericProducer, - accountUuid, - "/accounts/" + accountUuid + "/login-auth-modes", - "/accounts/" + accountUuid + "/login-auth-modes", - "{\"loginAuthModes\":[\"PASSWORD\"]}"); HttpResponse modesResponse = sendAccountRequest("GET", "/accounts/" + accountUuid + "/login-auth-modes", ordinary, null); @@ -1034,53 +1236,6 @@ void preparedAccountSelectorsRejectNumericProducerAndPreserveAuthorizationAndDen .isEqualTo(originalLoginModes); } - /** Test-owned caller proof for prepared HTTP readers; this does not qualify UUID issuance. */ - private String controlledUuidCallerAfterNumericProducerRefusal( - String numericProducer, - String accountUuid, - String readPath, - String writePath, - String writeBody) - throws Exception { - var claims = jwtUtil.parseToken(numericProducer).getPayload(); - Number privateAccountRow = - java.util.Objects.requireNonNull( - claims.get("accountId", Number.class), "Expected parent-issued numeric Account claim"); - assertThat(claims.getSubject()).isEqualTo(privateAccountRow.toString()); - assertThat( - dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", privateAccountRow) - .fetchOne(0, UUID.class)) - .isEqualTo(UUID.fromString(accountUuid)); - String accountBefore = - dsl.resultQuery( - "SELECT row_to_json(a)::text || ':' || a.xmin::text FROM accounts a WHERE id = ?", - privateAccountRow) - .fetchOne(0, String.class); - List profilesBefore = preparationProfileRows(privateAccountRow); - - assertThat(sendAccountRequest("GET", readPath, numericProducer, null).statusCode()) - .isEqualTo(401); - assertThat(sendAccountRequest("PUT", writePath, numericProducer, writeBody).statusCode()) - .isEqualTo(401); - assertThat( - dsl.resultQuery( - "SELECT row_to_json(a)::text || ':' || a.xmin::text FROM accounts a WHERE id = ?", - privateAccountRow) - .fetchOne(0, String.class)) - .isEqualTo(accountBefore); - assertThat(preparationProfileRows(privateAccountRow)).isEqualTo(profilesBefore); - - return jwtUtil.generateToken(accountUuid, java.util.Map.of("accountId", accountUuid)); - } - - private List preparationProfileRows(Number privateAccountRow) { - return dsl.resultQuery( - "SELECT row_to_json(p)::text || ':' || p.xmin::text FROM profiles p " - + "WHERE account_id = ? ORDER BY id", - privateAccountRow) - .fetch(0, String.class); - } - private HttpResponse sendAccountRequest( String method, String path, String token, String body) throws Exception { HttpRequest.Builder request = @@ -1100,10 +1255,8 @@ private HttpResponse sendAccountRequest( @Test void linkExternalRouteIsUnavailableWithAuthenticatedRequest() throws Exception { - String token = - jwtUtil.generateToken( - "d09f80cb-a46a-415e-8d35-c9e8068e49de", - java.util.Map.of("accountId", "d09f80cb-a46a-415e-8d35-c9e8068e49de")); + 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) @@ -1124,11 +1277,8 @@ void linkExternalRouteIsUnavailableWithAuthenticatedRequest() throws Exception { @Test void updateProfileRejectsZeroTenantIdWithInvalidArgumentEnvelope() throws Exception { - String token = - jwtUtil.generateToken( - "d09f80cb-a46a-415e-8d35-c9e8068e49de", - java.util.Map.of("accountId", "d09f80cb-a46a-415e-8d35-c9e8068e49de")); - String accountUuid = "d09f80cb-a46a-415e-8d35-c9e8068e49de"; + 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/" + accountUuid)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) @@ -1136,7 +1286,7 @@ void updateProfileRejectsZeroTenantIdWithInvalidArgumentEnvelope() throws Except .PUT( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":0,"accountId":"d09f80cb-a46a-415e-8d35-c9e8068e49de","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/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..42e9179213 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java @@ -0,0 +1,608 @@ +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()); + 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); + } + 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) {} +} 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/controller/AuthControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java index 233f84ee77..609772d54f 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 @@ -80,10 +80,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")); } @@ -109,7 +117,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( @@ -118,7 +126,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")); } @@ -126,7 +134,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( @@ -144,7 +152,7 @@ void playerBootstrapReturnsShortLivedToken() throws Exception { when(accountService.issuePlayerBootstrap("demo", "password")) .thenReturn( new PlayerBootstrapResult( - "10000000-0000-4000-8000-000000000001", + "4cae05e8-7a6b-4b14-9d44-665e3eec450b", "boot123", "2026-03-30T00:00:00Z", "2026-03-30T00:05:00Z")); @@ -156,7 +164,7 @@ void playerBootstrapReturnsShortLivedToken() throws Exception { .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.accountId").value("10000000-0000-4000-8000-000000000001")) + .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/PublicBootstrapRoutesProdProfileTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java index c4e5ee03ba..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,7 @@ void playerBootstrapRemainsPublicInProdProfile() throws Exception { when(accountService.issuePlayerBootstrap("demo@example.com", "swordfish")) .thenReturn( new PlayerBootstrapResult( - "10000000-0000-4000-8000-000000000001", + "4cae05e8-7a6b-4b14-9d44-665e3eec450b", "boot123", "2026-03-30T00:00:00Z", "2026-03-30T00:05:00Z")); @@ -52,7 +52,7 @@ void playerBootstrapRemainsPublicInProdProfile() throws Exception { .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.accountId").value("10000000-0000-4000-8000-000000000001")) + .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 index 480d15ce20..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 @@ -17,6 +17,7 @@ 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; @@ -31,7 +32,9 @@ 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; @@ -44,12 +47,12 @@ 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 PROFILE_UPDATE_METHOD = "account.v1.AccountService/UpdateProfile"; + 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 = "account.v1.AccountService/ListPresenceVisibilityPolicies"; - private static final String ACCOUNT_ID = "42"; + 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"; @@ -75,21 +78,22 @@ void realmGrantMethodAllowsOnlyExactSameNamespaceGameSessionWorkloadUnderBothYam 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_ID, Map.of("accountId", ACCOUNT_ID)); + 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_ID); - verify(accountService) - .getRealmAccessGrantForRuntime(42L, 1L, "demo", "preview", "req-1"); + assertThat(valid.observer().response.getAccountId()).isEqualTo(ACCOUNT_UUID); + verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); AccountService deniedService = mock(AccountService.class); AccountGrpcService deniedHandler = @@ -119,6 +123,8 @@ void exactSocialPeerReachesPresencePolicyHandlerWithoutBearerUnderBothYamlLayers productionLayer, (interceptor, ignored) -> { AccountService accountService = mock(AccountService.class); + 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 = @@ -131,15 +137,16 @@ void exactSocialPeerReachesPresencePolicyHandlerWithoutBearerUnderBothYamlLayers assertThat(result.observer().completed).isTrue(); assertThat(result.observer().response.getPoliciesCount()).isEqualTo(1); assertThat(result.observer().response.getPolicies(0).getAccountId()) - .isEqualTo(ACCOUNT_ID); + .isEqualTo(ACCOUNT_UUID); assertThat(result.observer().response.getPolicies(0).getPolicy()).isEqualTo("PRIVATE"); + verify(accountService).resolveAccountStorageIds(List.of(UUID.fromString(ACCOUNT_UUID))); verify(accountService).listPresenceVisibilityPolicies(1L, List.of(42L)); }); } } @Test - void bearerOnlyPresenceRequestReachesHandlerButIsDeniedWithoutSocialPeerUnderBothYamlLayers() { + void nonSocialPresenceRequestsReachHandlerButAreDeniedUnderBothYamlLayers() { for (boolean productionLayer : List.of(false, true)) { withConfiguredInterceptor( productionLayer, @@ -147,7 +154,23 @@ void bearerOnlyPresenceRequestReachesHandlerButIsDeniedWithoutSocialPeerUnderBot AccountService accountService = mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(mock(PingService.class), accountService, null, "test"); - String bearer = jwtUtil.generateToken(ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID)); + 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); @@ -158,14 +181,12 @@ void bearerOnlyPresenceRequestReachesHandlerButIsDeniedWithoutSocialPeerUnderBot "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"); - assertThat(wrongNamespace.handlerDispatched()).isTrue(); - assertThat(wrongNamespace.observer().completed).isTrue(); - assertThat(wrongNamespace.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); }); } @@ -204,7 +225,7 @@ public void onMessage(ListPresenceVisibilityPoliciesRequest request) { ListPresenceVisibilityPoliciesRequest request = ListPresenceVisibilityPoliciesRequest.newBuilder() .setTenantId("1") - .addAccountIds(ACCOUNT_ID) + .addAccountIds(ACCOUNT_UUID) .build(); Metadata headers = new Metadata(); if (bearerToken != null) { @@ -260,7 +281,7 @@ public void onMessage(GetRealmAccessGrantForRuntimeRequest request) { }; GetRealmAccessGrantForRuntimeRequest request = GetRealmAccessGrantForRuntimeRequest.newBuilder() - .setAccountId(ACCOUNT_ID) + .setAccountId(ACCOUNT_UUID) .setTenantId("1") .setWorldSlug("demo") .setRealmSlug("preview") @@ -328,8 +349,9 @@ private static void withConfiguredInterceptor( .contains(IDENTITY_METHOD) .contains(PRESENCE_METHOD) .contains(REALM_GRANT_METHOD) - .doesNotContain(NONPUBLIC_METHOD) - .doesNotContain(PROFILE_UPDATE_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 3fcf3c6a00..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 @@ -8,11 +8,14 @@ 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; 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; @@ -51,6 +54,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; @@ -58,16 +62,23 @@ 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; +import org.springframework.transaction.CannotCreateTransactionException; class AccountGrpcServiceTest { private static final String WORKLOAD_NAMESPACE = "test"; - private static final String PROFILE_ACCOUNT_UUID = "d09f80cb-a46a-415e-8d35-c9e8068e49de"; + 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"; private static final String PLAYABLE_STATE_NAMESPACE_ID = "c6ed6a44-c7e7-4f18-81fc-078a74e67c07"; @@ -76,20 +87,20 @@ class AccountGrpcServiceTest { "spiffe://firemud/ns/test/sa/game-session-service", WORKLOAD_NAMESPACE, "game-session-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 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) @@ -141,6 +152,31 @@ void tearDown() { SessionContext.clear(); } + private static Stream accountUuidReadbackFailures() { + return Stream.of( + new IllegalStateException(ACCOUNT_UUID_READBACK_FAILURE), + new DataAccessResourceFailureException(ACCOUNT_UUID_READBACK_FAILURE), + new CannotCreateTransactionException(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); @@ -171,6 +207,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), @@ -185,6 +223,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) @@ -279,20 +318,15 @@ 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), Mockito.any(JoinPublicProductionRequest.class))) .thenReturn( new JoinPublicProductionResult( - false, - "ENTITLEMENT_UNAVAILABLE", - "d09f80cb-a46a-415e-8d35-c9e8068e49de", - 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<>(); @@ -304,7 +338,7 @@ void joinPublicProductionMembershipPreservesStoredFailureOutcome() { assertTrue(observer.completed()); assertFalse(observer.response().getSuccess()); assertEquals("ENTITLEMENT_UNAVAILABLE", observer.response().getOutcomeCode()); - assertEquals("d09f80cb-a46a-415e-8d35-c9e8068e49de", observer.response().getAccountId()); + assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); assertEquals("20", observer.response().getTenantId()); assertEquals("0", observer.response().getMembershipId()); assertTrue(observer.response().getReplayed()); @@ -327,6 +361,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), @@ -351,6 +387,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), @@ -558,6 +596,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 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())) + .thenReturn( + new JoinPublicProductionResult( + false, + "ENTITLEMENT_UNAVAILABLE", + changedAccount ? OTHER_ACCOUNT_UUID : ACCOUNT_UUID, + 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); @@ -591,6 +691,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 authenticatePreservesAccountOwnerUnavailableAsApplicationError() { AccountService accountService = Mockito.mock(AccountService.class); @@ -691,7 +817,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<>(); @@ -714,10 +842,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); @@ -743,6 +894,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); @@ -888,34 +1065,79 @@ 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); - UUID accountUuid = UUID.fromString(PROFILE_ACCOUNT_UUID); - Mockito.when(accountService.resolveAccountStorageId(accountUuid)).thenReturn(2L); + 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, - PROFILE_ACCOUNT_UUID, - "demo", - "bio", - ProfilePresenceVisibilityPolicy.PRIVATE)); + 1L, 1L, ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE)); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - SessionContext.setContext(PROFILE_ACCOUNT_UUID, List.of("player"), Map.of()); AtomicReference ref = new AtomicReference<>(); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); withPeer( SOCIAL_GROUPS_PEER, () -> service.getProfile( - GetProfileRequest.newBuilder() - .setTenantId("1") - .setAccountId(PROFILE_ACCOUNT_UUID) - .build(), + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), new StreamObserver() { @Override public void onNext(GetProfileResponse value) { @@ -928,8 +1150,6 @@ public void onError(Throwable t) {} @Override public void onCompleted() {} })); - Mockito.verify(accountService).resolveAccountStorageId(accountUuid); - Mockito.verify(accountService).getProfile(1L, 2L); assertEquals( "demo", @@ -939,7 +1159,7 @@ public void onCompleted() {} .get("displayName") .asText()); assertEquals( - PROFILE_ACCOUNT_UUID, + ACCOUNT_UUID, tools.jackson.databind.json.JsonMapper.builder() .build() .readTree(ref.get().getProfileJson()) @@ -952,16 +1172,18 @@ public void onCompleted() {} .readTree(ref.get().getProfileJson()) .path("presenceVisibilityPolicy") .asText()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); } @Test - void getProfileRejectsNumericAccountIdBeforeLookup() { + void getProfileRejectsZeroAccountIdBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); withPeer( SOCIAL_GROUPS_PEER, () -> @@ -987,160 +1209,532 @@ public void onCompleted() {} } @Test - void getProfileRejectsDifferentCallerSubjectBeforeResolvingOwner() { + void getProfileRejectsMismatchedCallerSubjectBeforeStorageResolution() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - SessionContext.setContext("a2e1342e-a139-49c6-a460-c8e25f6697ae", List.of("player"), Map.of()); 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(PROFILE_ACCOUNT_UUID) - .build(), + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), observer)); assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); - Mockito.verifyNoInteractions(accountService); + Mockito.verify(accountService, Mockito.never()) + .resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService, Mockito.never()).getProfile(1L, 2L); } - @Test - void listPresenceVisibilityPoliciesMapsPersistedPolicies() { - PingService pingService = Mockito.mock(PingService.class); + @ParameterizedTest + @ValueSource(strings = {"resolution", "profile"}) + void getProfileBoundsUnprovedIdentityAndUnavailableAuthority(String failureStage) { AccountService accountService = Mockito.mock(AccountService.class); - 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, null, WORKLOAD_NAMESPACE); - RecordingObserver observer = new RecordingObserver<>(); + 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.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("2") - .addAccountIds("3") - .addAccountIds("2") - .build(), + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), observer)); - assertNotNull(observer.response()); - assertEquals(2, observer.response().getPoliciesCount()); - assertTrue( - observer.response().getPoliciesList().stream() - .anyMatch( - entry -> entry.getAccountId().equals("2") && entry.getPolicy().equals("PRIVATE"))); - assertTrue( - observer.response().getPoliciesList().stream() - .anyMatch( - entry -> - entry.getAccountId().equals("3") && entry.getPolicy().equals("HIDDEN_STAFF"))); + assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); + assertEquals( + "Account authority unavailable; retry later", observer.response().getError().getMessage()); assertTrue(observer.completed()); assertFalse(observer.receivedTransportError()); - Mockito.verify(accountService).listPresenceVisibilityPolicies(1L, List.of(2L, 3L)); } - @Test - void listPresenceVisibilityPoliciesRejectsNonPositiveAccountId() { - PingService pingService = Mockito.mock(PingService.class); + @ParameterizedTest + @ValueSource(strings = {"resolution", "profile"}) + void updateProfileBoundsUnprovedIdentityAndUnavailableAuthority(String failureStage) { AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = - new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - RecordingObserver observer = new RecordingObserver<>(); + 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.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() + service.updateProfile( + UpdateProfileRequest.newBuilder() .setTenantId("1") - .addAccountIds("0") + .setAccountId(ACCOUNT_UUID) + .setProfileJson( + "{\"displayName\":\"demo\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") .build(), observer)); - assertNotNull(observer.response()); - assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); - assertEquals("accountId must be positive", observer.response().getError().getMessage()); + 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()); - Mockito.verifyNoInteractions(accountService); } @Test - void listPresenceVisibilityPoliciesMapsServiceRuntimeFailuresToApplicationErrors() { - PingService pingService = Mockito.mock(PingService.class); + void profileMethodsPreserveMissingAccountOutcome() { AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = - new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + 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<>(); - Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) - .thenThrow(new IllegalArgumentException("Tenant not found")); - RecordingObserver notFoundObserver = - new RecordingObserver<>(); withPeer( SOCIAL_GROUPS_PEER, - () -> - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("2") - .build(), - notFoundObserver)); + () -> { + 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", notFoundObserver.response().getError().getCode()); - assertTrue(notFoundObserver.completed()); - assertFalse(notFoundObserver.receivedTransportError()); + 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<>(); - Mockito.reset(accountService); - Mockito.when(accountService.listPresenceVisibilityPolicies(1L, List.of(2L))) - .thenThrow(new IllegalStateException("Policy lookup unavailable")); - RecordingObserver internalObserver = - new RecordingObserver<>(); withPeer( SOCIAL_GROUPS_PEER, - () -> - service.listPresenceVisibilityPolicies( - ListPresenceVisibilityPoliciesRequest.newBuilder() - .setTenantId("1") - .addAccountIds("2") - .build(), - internalObserver)); + () -> { + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(accountUuid).build(), + getObserver); + service.updateProfile( + UpdateProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(accountUuid) + .setProfileJson("{}") + .build(), + updateObserver); + }); - assertEquals("INTERNAL", internalObserver.response().getError().getCode()); - assertTrue(internalObserver.completed()); - assertFalse(internalObserver.receivedTransportError()); + assertEquals("INVALID_ARGUMENT", getObserver.response().getError().getCode()); + assertEquals("INVALID_ARGUMENT", updateObserver.response().getError().getCode()); + assertTrue(getObserver.completed()); + assertTrue(updateObserver.completed()); + Mockito.verifyNoInteractions(accountService); } - @Test - void getTenantMembershipForRuntimeReturnsResponse() { - PingService pingService = Mockito.mock(PingService.class); + @ParameterizedTest + @ValueSource( + strings = { + "", + "{", + "null", + "[]", + "{\"presenceVisibilityPolicy\":\"UNKNOWN\"}", + "{}", + "{\"presenceVisibilityPolicy\":null}", + "{\"presenceVisibilityPolicy\":17}", + "{\"presenceVisibilityPolicy\":\"HIDDEN_STAFF\"}" + }) + void updateProfileRejectsMalformedJsonAndPolicyWithInvalidArgument(String profileJson) { AccountService accountService = Mockito.mock(AccountService.class); - 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, null, WORKLOAD_NAMESPACE); + 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<>(); - AtomicReference ref = new AtomicReference<>(); withPeer( - GAME_SESSION_PEER, + SOCIAL_GROUPS_PEER, () -> - service.getTenantMembershipForRuntime( - GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") + service.updateProfile( + UpdateProfileRequest.newBuilder() .setTenantId("1") - .setRequestId("req-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 listPresenceVisibilityPoliciesResolvesAndReturnsCanonicalUuidKeysForSocialPeer() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + 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( + 2L, ProfilePresenceVisibilityPolicy.PRIVATE, + 3L, ProfilePresenceVisibilityPolicy.HIDDEN_STAFF)); + 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, 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(ACCOUNT_UUID) + && entry.getPolicy().equals("PRIVATE"))); + assertTrue( + observer.response().getPoliciesList().stream() + .anyMatch( + entry -> + entry.getAccountId().equals(OTHER_ACCOUNT_UUID) + && entry.getPolicy().equals("HIDDEN_STAFF"))); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + Mockito.verify(accountService) + .resolveAccountStorageIds( + List.of(UUID.fromString(ACCOUNT_UUID), UUID.fromString(OTHER_ACCOUNT_UUID))); + Mockito.verify(accountService).listPresenceVisibilityPolicies(1L, List.of(2L, 3L)); + } + + @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, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + presencePolicyRequest(ACCOUNT_UUID, accountId), observer)); + + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService); + } + + @Test + void listPresenceVisibilityPoliciesRejectsOverLimitBeforeResolution() { + 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<>(); + String[] accountUuids = + java.util.stream.LongStream.rangeClosed(1L, 101L) + .mapToObj(value -> new UUID(0L, value).toString()) + .toArray(String[]::new); + + 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.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 = + 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) + .resolveAccountStorageIds( + List.of( + UUID.fromString(ACCOUNT_UUID), + UUID.fromString(OTHER_ACCOUNT_UUID), + UUID.fromString(unprovenAccountUuid))); + 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.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<>(); + + 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.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 = + 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.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 = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver notFoundObserver = + new RecordingObserver<>(); + + 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.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 = + new RecordingObserver<>(); + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.listPresenceVisibilityPolicies( + presencePolicyRequest(ACCOUNT_UUID), internalObserver)); + + assertEquals("INTERNAL", internalObserver.response().getError().getCode()); + assertTrue(internalObserver.completed()); + assertFalse(internalObserver.receivedTransportError()); + } + + @Test + 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, null, WORKLOAD_NAMESPACE); + + AtomicReference ref = new AtomicReference<>(); + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("1") + .setRequestId("req-1") .build(), new StreamObserver() { @Override @@ -1156,16 +1750,20 @@ 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( @@ -1179,13 +1777,14 @@ void getTenantMembershipForRuntimePreservesMissingMembershipAndAdmissionAllowed( () -> service.getTenantMembershipForRuntime( GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") + .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()); @@ -1205,7 +1804,7 @@ void getTenantMembershipForRuntimeRejectsZeroTenantIdBeforeLookup() { () -> service.getTenantMembershipForRuntime( GetTenantMembershipForRuntimeRequest.newBuilder() - .setAccountId("2") + .setAccountId(ACCOUNT_UUID) .setTenantId("0") .setRequestId("req-1") .build(), @@ -1228,105 +1827,411 @@ 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 getTenantMembershipForRuntimeRejectsNonGameSessionPeer() { + void getTenantMembershipForRuntimeRejectsMissingGameSessionPeer() { 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<>(); + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("1") + .setRequestId("req-1") + .build(), + observer); + + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.completed()); + Mockito.verifyNoInteractions(accountService); + } + + @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<>(); + withPeer( - SOCIAL_GROUPS_PEER, + 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("2") + .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 getRealmAccessGrantForRuntimeRejectsZeroAccountIdBeforeLookup() { + 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()); + 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 + void getTenantEntitlementsForRuntimeReturnsResponse() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.getTenantEntitlementsForRuntime(1L, "req-2")) + .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); - AtomicReference ref = new AtomicReference<>(); + RecordingObserver observer = new RecordingObserver<>(); withPeer( GAME_SESSION_PEER, () -> - service.getRealmAccessGrantForRuntime( - GetRealmAccessGrantForRuntimeRequest.newBuilder() - .setAccountId("0") + service.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() .setTenantId("1") - .setWorldSlug("demo") - .setRealmSlug("production") - .setRequestId("req-1") + .setRequestId("req-2") .build(), - new StreamObserver() { - @Override - public void onNext(GetRealmAccessGrantForRuntimeResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - })); + observer)); - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(accountService); + 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"); } @Test - void getTenantEntitlementsForRuntimeReturnsResponse() { + void getTenantEntitlementsForRuntimeAllowsWorldManagementPeer() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.getTenantEntitlementsForRuntime(1L, "req-2")) + 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<>(); - AtomicReference ref = new AtomicReference<>(); withPeer( - GAME_SESSION_PEER, + WORLD_MANAGEMENT_PEER, () -> service.getTenantEntitlementsForRuntime( GetTenantEntitlementsForRuntimeRequest.newBuilder() .setTenantId("1") - .setRequestId("req-2") + .setRequestId("req-world") .build(), - new StreamObserver() { - @Override - public void onNext(GetTenantEntitlementsForRuntimeResponse value) { - ref.set(value); - } + observer)); - @Override - public void onError(Throwable t) {} + assertEquals("1", observer.response().getTenantId()); + assertTrue(observer.completed()); + Mockito.verify(accountService).getTenantEntitlementsForRuntime(1L, "req-world"); + } - @Override - public void onCompleted() {} - })); + @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")); - assertNotNull(ref.get()); - assertEquals("1", ref.get().getTenantId()); - assertTrue(ref.get().getGameplayAvailable()); - assertTrue(ref.get().getAllowPublicJoin()); - assertEquals(19L, ref.get().getEntitlementVersion()); + 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 @@ -1368,55 +2273,6 @@ public void onCompleted() {} assertEquals("ENTITLEMENT_UNAVAILABLE", ref.get().getError().getCode()); } - @Test - void getTenantEntitlementsForRuntimeAllowsExactWorldManagementPeer() { - PingService pingService = Mockito.mock(PingService.class); - AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.getTenantEntitlementsForRuntime(1L, "req-2")) - .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<>(); - - withPeer( - WORLD_MANAGEMENT_PEER, - () -> - service.getTenantEntitlementsForRuntime( - GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") - .setRequestId("req-2") - .build(), - observer)); - - assertTrue(observer.completed()); - assertEquals("1", observer.response().getTenantId()); - Mockito.verify(accountService).getTenantEntitlementsForRuntime(1L, "req-2"); - } - - @Test - void getTenantEntitlementsForRuntimeRejectsNonAuthorizedPeer() { - PingService pingService = Mockito.mock(PingService.class); - AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = - new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - RecordingObserver observer = new RecordingObserver<>(); - - withPeer( - SOCIAL_GROUPS_PEER, - () -> - service.getTenantEntitlementsForRuntime( - GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") - .setRequestId("req-2") - .build(), - observer)); - - assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); - Mockito.verifyNoInteractions(accountService); - } - @Test void getTenantEntitlementsForRuntimeRejectsZeroTenantIdBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); @@ -1457,20 +2313,20 @@ public void onCompleted() {} void updateProfileResolvesUuidOwnerAfterCallerCheck(String policyName) { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - UUID accountUuid = UUID.fromString(PROFILE_ACCOUNT_UUID); + UUID accountUuid = UUID.fromString(ACCOUNT_UUID); Mockito.when(accountService.resolveAccountStorageId(accountUuid)).thenReturn(2L); Mockito.when(accountService.updateProfile(Mockito.any())) .thenReturn( new net.firedevops.firemud.accountservice.dto.ProfileDto( 1L, 1L, - PROFILE_ACCOUNT_UUID, + ACCOUNT_UUID, "demo", "bio", ProfilePresenceVisibilityPolicy.valueOf(policyName))); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - SessionContext.setContext(PROFILE_ACCOUNT_UUID, List.of("player"), Map.of()); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); RecordingObserver observer = new RecordingObserver<>(); withPeer( @@ -1479,7 +2335,7 @@ void updateProfileResolvesUuidOwnerAfterCallerCheck(String policyName) { service.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("1") - .setAccountId(PROFILE_ACCOUNT_UUID) + .setAccountId(ACCOUNT_UUID) .setProfileJson( "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"" + policyName @@ -1494,92 +2350,33 @@ void updateProfileResolvesUuidOwnerAfterCallerCheck(String policyName) { net.firedevops.firemud.accountservice.dto.UpdateProfileRequest.class); Mockito.verify(accountService).resolveAccountStorageId(accountUuid); Mockito.verify(accountService).updateProfile(requestCaptor.capture()); - assertEquals(PROFILE_ACCOUNT_UUID, requestCaptor.getValue().accountId()); + assertEquals(ACCOUNT_UUID, requestCaptor.getValue().accountId()); assertEquals(1L, requestCaptor.getValue().tenantId()); assertEquals( ProfilePresenceVisibilityPolicy.valueOf(policyName), requestCaptor.getValue().presenceVisibilityPolicy()); } - @ParameterizedTest - @ValueSource( - strings = { - "{\"displayName\":\"demo\"}", - "{\"displayName\":\"demo\",\"presenceVisibilityPolicy\":null}", - "{\"displayName\":\"demo\",\"presenceVisibilityPolicy\":\"UNKNOWN\"}" - }) - void updateProfileRejectsMissingNullOrInvalidVisibilityPolicy(String profileJson) { - PingService pingService = Mockito.mock(PingService.class); - AccountService accountService = Mockito.mock(AccountService.class); - UUID accountUuid = UUID.fromString(PROFILE_ACCOUNT_UUID); - Mockito.when(accountService.resolveAccountStorageId(accountUuid)).thenReturn(2L); - AccountGrpcService service = - new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - SessionContext.setContext(PROFILE_ACCOUNT_UUID, List.of("player"), Map.of()); - RecordingObserver observer = new RecordingObserver<>(); - - withPeer( - SOCIAL_GROUPS_PEER, - () -> - service.updateProfile( - UpdateProfileRequest.newBuilder() - .setTenantId("1") - .setAccountId(PROFILE_ACCOUNT_UUID) - .setProfileJson(profileJson) - .build(), - observer)); - - assertFalse(observer.response().getSuccess()); - assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); - Mockito.verify(accountService, Mockito.never()).updateProfile(Mockito.any()); - } - - @Test - void updateProfileRejectsDifferentCallerSubjectBeforeResolvingOwner() { - PingService pingService = Mockito.mock(PingService.class); - AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = - new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - SessionContext.setContext("a2e1342e-a139-49c6-a460-c8e25f6697ae", List.of("player"), Map.of()); - RecordingObserver observer = new RecordingObserver<>(); - - withPeer( - SOCIAL_GROUPS_PEER, - () -> - service.updateProfile( - UpdateProfileRequest.newBuilder() - .setTenantId("1") - .setAccountId(PROFILE_ACCOUNT_UUID) - .setProfileJson( - "{\"displayName\":\"demo\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") - .build(), - observer)); - - assertFalse(observer.response().getSuccess()); - assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); - Mockito.verifyNoInteractions(accountService); - } - @Test void updateProfileErrorReturnsDetail() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(PROFILE_ACCOUNT_UUID))) - .thenReturn(2L); Mockito.when(accountService.updateProfile(Mockito.any())) .thenThrow(new IllegalArgumentException("bad")); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - SessionContext.setContext(PROFILE_ACCOUNT_UUID, List.of("player"), Map.of()); AtomicReference ref = new AtomicReference<>(); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); withPeer( SOCIAL_GROUPS_PEER, () -> service.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("1") - .setAccountId(PROFILE_ACCOUNT_UUID) + .setAccountId(ACCOUNT_UUID) .setProfileJson( "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") .build(), @@ -1604,23 +2401,23 @@ public void onCompleted() {} void updateProfilePreservesUnavailableOwnerProjectionResponse() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(PROFILE_ACCOUNT_UUID))) - .thenReturn(2L); String message = "Account owner projection is unavailable"; Mockito.when(accountService.updateProfile(Mockito.any())) .thenThrow(new AuthenticationException("AUTH_UNAVAILABLE", message)); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - SessionContext.setContext(PROFILE_ACCOUNT_UUID, List.of("player"), Map.of()); RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); withPeer( SOCIAL_GROUPS_PEER, () -> service.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("1") - .setAccountId(PROFILE_ACCOUNT_UUID) + .setAccountId(ACCOUNT_UUID) .setProfileJson( "{\"displayName\":\"demo\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") .build(), @@ -1648,7 +2445,7 @@ void updateProfileRejectsZeroTenantIdBeforeUpdate() { service.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("0") - .setAccountId(PROFILE_ACCOUNT_UUID) + .setAccountId(ACCOUNT_UUID) .setProfileJson( "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") .build(), @@ -1677,11 +2474,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) { @@ -1706,10 +2505,14 @@ void exportAccountPreservesUnavailableOwnerProjectionResponse() { String message = "Account owner projection is unavailable"; Mockito.when(accountService.exportAccountData(2L)) .thenThrow(new AuthenticationException("AUTH_UNAVAILABLE", message)); - 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); RecordingObserver observer = new RecordingObserver<>(); - service.exportAccount(ExportAccountRequest.newBuilder().setAccountId("2").build(), observer); + service.exportAccount( + ExportAccountRequest.newBuilder().setAccountId(ACCOUNT_UUID).build(), observer); assertEquals(1, observer.nextCalls); assertEquals(0, observer.receivedTransportError() ? 1 : 0); @@ -1725,11 +2528,15 @@ void exportTenantDataPreservesUnavailableOwnerProjectionResponse() { String message = "Account owner projection is unavailable"; Mockito.when(accountService.exportTenantData(1L, 2L)) .thenThrow(new AuthenticationException("AUTH_UNAVAILABLE", message)); - 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); RecordingObserver observer = new RecordingObserver<>(); service.exportTenantData( - ExportTenantDataRequest.newBuilder().setTenantId("1").setAccountId("2").build(), observer); + ExportTenantDataRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), + observer); assertEquals(1, observer.nextCalls); assertEquals(0, observer.receivedTransportError() ? 1 : 0); @@ -1762,7 +2569,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); } @@ -1798,12 +2605,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) { @@ -1847,7 +2656,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); } @@ -1855,6 +2664,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 = @@ -1862,7 +2673,7 @@ void linkExternalAccountSuccess() { service.linkExternalAccount( net.firedevops.firemud.account.v1.LinkExternalAccountRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(ACCOUNT_UUID) .setProvider("google") .setExternalId("abc") .build(), @@ -1947,10 +2758,107 @@ 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); } + @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/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 8b63ba5a47..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; @@ -342,13 +343,8 @@ void ordinaryIssuanceKeepsItsProfileContractAfterExactOwnerReadback(OrdinaryIssu String token = issueOrdinaryCredential(mode); var claims = jwtUtil.parseToken(token).getPayload(); - if (mode == OrdinaryIssuance.PLAYER_BOOTSTRAP) { - assertEquals(account.getAccountUuid().toString(), claims.getSubject()); - assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); - } else { - assertEquals("42", claims.getSubject()); - assertEquals(42L, ((Number) claims.get("accountId")).longValue()); - } + 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); @@ -394,7 +390,7 @@ private Account ordinaryIssuanceAccount() { account.setEmailVerified(true); account.setLoginAuthModes("PASSWORD,EMAIL_OTP"); account.setPasswordHash(hash("password")); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); when(accountRepository.findByEmail("owner@example.com")).thenReturn(Optional.of(account)); return account; } @@ -426,7 +422,8 @@ private String issueOrdinaryCredential(OrdinaryIssuance mode) { case EMAIL_OTP -> service.verifyEmailLoginOtp("owner@example.com", "123456"); case PLAYER_BOOTSTRAP -> throw new IllegalStateException("Bootstrap handled above"); }; - assertEquals(42L, result.accountId()); + assertEquals( + jwtUtil.parseToken(result.authToken()).getPayload().getSubject(), result.accountId()); return result.authToken(); } @@ -545,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 = @@ -632,7 +686,7 @@ void createAccountMapsSpringDataIntegrityConflict() { void joinPublicProductionRetainsReceiptAfterProjectionFailureAndReplaysWithoutDuplicateEffects() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -856,7 +910,7 @@ void joinPublicProductionRejectsStillActiveBootstrapForIneligibleLifecycleState( AccountLifecycleState lifecycleState, String expectedCode) { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -889,7 +943,7 @@ void joinPublicProductionRejectsStillActiveBootstrapForIneligibleLifecycleState( void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -945,7 +999,7 @@ void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembership() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1033,7 +1087,7 @@ void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembers void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguous) { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1116,7 +1170,7 @@ void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguou void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1183,7 +1237,7 @@ void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1250,7 +1304,7 @@ void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { void unboundFailedJoinReplaysOnlyAfterCurrentScopeAndAuthorityChecks() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1373,7 +1427,7 @@ void unboundFailedJoinReplaysOnlyAfterCurrentScopeAndAuthorityChecks() { void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1419,7 +1473,7 @@ void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTransition() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1531,7 +1585,7 @@ void expiredPersistedPendingJoinFailsTerminallyWithoutAuthorityOrMembershipTrans void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1643,7 +1697,7 @@ void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredSuccess() { void joinPublicProductionHidesAnotherAccountsGlobalRequestIdEvidence(String originalStatus) { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1742,7 +1796,7 @@ void joinPublicProductionHidesAnotherAccountsGlobalRequestIdEvidence(String orig void reclaimedScopeRaceReturnsConnectScopeInvalid() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1789,7 +1843,7 @@ void reclaimedScopeRaceReturnsConnectScopeInvalid() { void quarantinedLegacyMembershipIsNeverRestoredByPublicJoin() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2058,7 +2112,7 @@ void emailLoginOtpRequestPersistsOnlyHashedChallengeAndSendsSixDigitCode() { void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { Account account = new Account(); account.setId(9L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setEmail("verified@example.com"); account.setEmailVerified(true); account.setRole("player"); @@ -2091,7 +2145,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()); @@ -2107,7 +2161,7 @@ void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { Account account = new Account(); account.setId(9L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = @@ -2122,7 +2176,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()); @@ -2133,7 +2187,7 @@ void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { void authenticateFallsBackToPasswordWithoutBurningUnmatchedEmailLoginOtp() { Account account = new Account(); account.setId(9L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = @@ -2148,7 +2202,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()) @@ -2159,7 +2213,7 @@ void authenticateFallsBackToPasswordWithoutBurningUnmatchedEmailLoginOtp() { void authenticateCountsFailedMixedModeSecretAgainstActiveEmailLoginOtp() { Account account = new Account(); account.setId(9L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = @@ -2199,6 +2253,59 @@ 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)); + + 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); + 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()); @@ -2216,7 +2323,7 @@ void emailLoginOtpVerificationFailsClosedForUnknownEmail() { void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { Account account = new Account(); account.setId(9L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setEmail("verified@example.com"); account.setRole("player"); net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = @@ -2232,10 +2339,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); @@ -2246,7 +2354,7 @@ void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { void authenticateReturnsControlUiTokenWithoutGameplayMembership() { Account account = new Account(); account.setId(1L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2254,10 +2362,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")); @@ -2276,7 +2385,7 @@ void authenticateRejectsIneligibleLifecycleState( AccountLifecycleState lifecycleState, String expectedCode) { Account account = new Account(); account.setId(1L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); account.setLifecycleState(lifecycleState); @@ -2293,7 +2402,7 @@ void authenticateRejectsIneligibleLifecycleState( void authenticateForGameplayReturnsTokenWhenPasswordMatches() { Account account = new Account(); account.setId(1L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); @@ -2302,10 +2411,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) @@ -2317,7 +2427,7 @@ void authenticateForGameplayReturnsTokenWhenPasswordMatches() { void issuePlayerBootstrapReturnsShortLivedToken() { Account account = new Account(); account.setId(7L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); account.setLoginAuthModes("PASSWORD"); @@ -2337,16 +2447,54 @@ 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)); + + 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); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(challenge); + verifyNoInteractions(sessionService); + } + @Test void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { Account emailAccount = new Account(); emailAccount.setId(7L); - retainAuthenticationIdentity(emailAccount); + setPersistedAuthenticationIdentity(emailAccount); emailAccount.setUsername("email-owner"); emailAccount.setEmail("player@example.com"); emailAccount.setPasswordHash(hash("password")); @@ -2365,7 +2513,7 @@ void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { Account account = new Account(); account.setId(7L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setEmail("demo@example.com"); account.setLoginAuthModes("EMAIL_OTP"); @@ -2465,7 +2613,7 @@ void bootstrapReaderReportsOwnerReadbackFailureBeforeSessionUse(String failure) void bootstrapReaderResolvesUuidBeforeReadingPrivateAccountSession() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); String uuid = account.getAccountUuid().toString(); String token = new JwtUtil(JWT_SECRET, 300000L) @@ -2483,13 +2631,12 @@ void bootstrapReaderResolvesUuidBeforeReadingPrivateAccountSession() { void listBootstrapWorldsRejectsInactiveAccountBootstrapToken() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); + String accountUuid = account.getAccountUuid().toString(); String bootstrapToken = new JwtUtil(JWT_SECRET, 300000L) .generateToken( - account.getAccountUuid().toString(), - Map.of( - "aud", "player-bootstrap", "accountId", account.getAccountUuid().toString())); + accountUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); AuthenticationException ex = assertThrows( @@ -2500,13 +2647,22 @@ void listBootstrapWorldsRejectsInactiveAccountBootstrapToken() { org.mockito.Mockito.verify(sessionService).isAccountSessionActive(11L, bootstrapToken); } - @Test - void listBootstrapWorldsRejectsMalformedBootstrapTokenAccountClaim() { + @ParameterizedTest + @ValueSource( + strings = { + "not-a-uuid", + "abc", + "0", + "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( - "10000000-0000-4000-8000-000000000001", - Map.of("aud", "player-bootstrap", "accountId", "abc")); + accountUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); AuthenticationException ex = assertThrows( @@ -2514,6 +2670,7 @@ void listBootstrapWorldsRejectsMalformedBootstrapTokenAccountClaim() { () -> service.listBootstrapWorlds(malformedBootstrapToken)); assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + verifyNoInteractions(accountRepository, sessionService); } @Test @@ -2521,12 +2678,8 @@ void listBootstrapWorldsRejectsBootstrapTokenAccountSubjectMismatch() { String malformedBootstrapToken = new JwtUtil(JWT_SECRET, 300000L) .generateToken( - "10000000-0000-4000-8000-000000000001", - Map.of( - "aud", - "player-bootstrap", - "accountId", - "10000000-0000-4000-8000-000000000002")); + REALM_ID, + Map.of("aud", "player-bootstrap", "accountId", PLAYABLE_STATE_NAMESPACE_ID)); AuthenticationException ex = assertThrows( @@ -2534,15 +2687,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( - "10000000-0000-4000-8000-000000000001", - Map.of("aud", "player-bootstrap", "accountId", "0")); + .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "11")); AuthenticationException ex = assertThrows( @@ -2614,7 +2766,7 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2654,7 +2806,7 @@ void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { void listBootstrapRealmsMapsZeroPublicAuthorityFromGameSession() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2678,7 +2830,7 @@ void listBootstrapRealmsMapsZeroPublicAuthorityFromGameSession() { void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2717,7 +2869,7 @@ void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { void listBootstrapRealmsRejectsMultipleVisiblePublicRealms() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2746,7 +2898,7 @@ void listBootstrapRealmsRejectsMultipleVisiblePublicRealms() { void listBootstrapRealmsAcceptsExactlyOneVisiblePublicRealm() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2785,7 +2937,7 @@ void bootstrapRealmDiscoveryAndDirectTextScopeIssuanceSuspendIncomingTransaction void listBootstrapRealmsDoesNotIssueScopeWhenPublicPointerBecomesPrivateBeforeFinalRead() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2821,7 +2973,7 @@ void listBootstrapRealmsDoesNotIssueScopeWhenPublicPointerBecomesPrivateBeforeFi void listBootstrapRealmsDoesNotIssueScopeWhenPointerChangesDuringDiscovery() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2857,7 +3009,7 @@ void listBootstrapRealmsDoesNotIssueScopeWhenPointerChangesDuringDiscovery() { void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2897,7 +3049,7 @@ void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { void issueConnectTokenRejectsMalformedConnectScopeId() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2923,11 +3075,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); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2957,7 +3167,7 @@ void issueConnectTokenRejectsBlankConnectScopeId() { void issueConnectTokenRejectsNonPositiveConnectScopeClaims() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3011,7 +3221,7 @@ void issueConnectTokenRejectsNonPositiveConnectScopeClaims() { void issueConnectTokenRejectsMalformedConnectScopeClaims() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3066,7 +3276,7 @@ void issueConnectTokenRejectsMalformedConnectScopeClaims() { void issueConnectTokenRejectsNoncanonicalRealmIdClaims(String realmId) { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3119,7 +3329,7 @@ void issueConnectTokenRejectsNoncanonicalRealmIdClaims(String realmId) { void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3137,7 +3347,7 @@ void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { String malformedConnectScopeId = new JwtUtil(JWT_SECRET, 120000L) .generateToken( - "10000000-0000-4000-8000-000000000012", + "4d3e9d15-a02e-41db-8648-0d2c68d0f0a3", Map.of( "aud", "bootstrap-connect-scope", @@ -3173,7 +3383,7 @@ void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { void issueConnectTokenRejectsBlankWorldSlugConnectScopeClaims() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3227,7 +3437,7 @@ void issueConnectTokenRejectsBlankWorldSlugConnectScopeClaims() { void issueConnectTokenRejectsZeroPointerVersionInConnectScopeClaims() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3281,7 +3491,7 @@ void issueConnectTokenRejectsZeroPointerVersionInConnectScopeClaims() { void authenticateForGameplayUsesNormalizedEmailLookup() { Account account = new Account(); account.setId(1L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); @@ -3291,7 +3501,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); @@ -3326,13 +3536,13 @@ void authenticateDoesNotUseGlobalAccountFallback() { void authenticateAllowsGlobalIdentityWithoutTenantMembership() { Account account = new Account(); account.setId(7L); - retainAuthenticationIdentity(account); + 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()); @@ -3343,6 +3553,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")); @@ -3375,6 +3586,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")); @@ -3669,7 +3881,7 @@ void issueConnectTokenDoesNotReturnCachedLegacySuccess() { private ConnectScopeFixture prepareConnectScopeForIssue() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3726,7 +3938,7 @@ private record ConnectScopeFixture(String bootstrapToken, String connectScopeId) void listBootstrapCharactersUsesEntityManagementForResolvedRealm() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3745,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"); @@ -3762,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 @@ -3770,7 +3985,7 @@ void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( boolean membershipExists) { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3818,7 +4033,7 @@ void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( void listBootstrapCharactersChecksPublicJoinPolicyBeforeReturningJoinRequired() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3855,7 +4070,7 @@ void listBootstrapCharactersClassifiesInactivePublicMembershipByJoinPolicy( String subscriptionStatus, String expectedCode) { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3896,7 +4111,7 @@ void listBootstrapCharactersClassifiesInactivePublicMembershipByJoinPolicy( void listBootstrapCharactersKeepsSelectedTargetFailClosedWhenEntitlementsAreUnavailable() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3930,7 +4145,7 @@ void listBootstrapCharactersKeepsSelectedTargetFailClosedWhenEntitlementsAreUnav void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDiscovery() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4000,7 +4215,7 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4054,7 +4269,7 @@ void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { void listBootstrapCharactersSkipsMalformedUnrelatedRealm() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4104,7 +4319,7 @@ void listBootstrapCharactersSkipsMalformedUnrelatedRealm() { void listBootstrapRealmsIncludesRealmStatePolicy() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4119,6 +4334,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) @@ -4143,7 +4364,7 @@ void listBootstrapRealmsRejectsNoncanonicalPlayableStateNamespaceIdFromReachable String namespaceId) { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4182,10 +4403,10 @@ void listBootstrapRealmsRejectsNoncanonicalPlayableStateNamespaceIdFromReachable } @Test - void listBootstrapRealmsReadsFreshEntitlementsOncePerTenantPerInvocation() { + void listBootstrapRealmsReadsFreshEntitlementsAndReusesVerifiedAccountIdentity() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4253,19 +4474,29 @@ 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, 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) { + 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); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4315,7 +4546,7 @@ void listBootstrapWorldsReadsFreshEntitlementsOncePerTenantPerInvocation() { void listBootstrapWorldsOmitsCanceledTenantAndFailsWhenEntitlementIsUnavailable() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4399,7 +4630,7 @@ void listBootstrapWorldsOmitsCanceledTenantAndFailsWhenEntitlementIsUnavailable( void listBootstrapRealmsPropagatesUnavailableEntitlements() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4420,7 +4651,7 @@ void listBootstrapRealmsPropagatesUnavailableEntitlements() { void listBootstrapWorldsFailsInsteadOfReturningIncompleteWorldDiscovery() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4474,7 +4705,7 @@ void listBootstrapWorldsFailsInsteadOfReturningIncompleteWorldDiscovery() { void listBootstrapRealmsRethrowsOtherAuthenticationErrors() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4516,7 +4747,7 @@ void listBootstrapRealmsRethrowsOtherAuthenticationErrors() { void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4574,7 +4805,7 @@ void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { void listBootstrapRealmsRejectsRealmWithUnknownStateScope() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4616,7 +4847,7 @@ void listBootstrapRealmsRejectsRealmWithUnknownStateScope() { void listBootstrapCharactersUsesIsolatedRealmRoster() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4669,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"); @@ -4692,7 +4923,7 @@ void listBootstrapCharactersUsesIsolatedRealmRoster() { void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4741,7 +4972,7 @@ void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4790,7 +5021,7 @@ void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicatesAcrossWorlds() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4862,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"); @@ -4889,7 +5120,7 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4939,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"); @@ -4965,7 +5196,7 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { void listBootstrapCharactersRejectsPathThatDoesNotMatchSignedScope() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4993,7 +5224,7 @@ void listBootstrapCharactersRejectsPathThatDoesNotMatchSignedScope() { void listBootstrapCharactersRejectsChangedCanonicalRealmId() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5032,7 +5263,7 @@ void listBootstrapCharactersRejectsChangedCanonicalRealmId() { void listBootstrapRealmsExcludesNonPublicRealmWithoutGrant() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5081,7 +5312,7 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( boolean visible, boolean publicProductionRealm) { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5146,7 +5377,7 @@ void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( boolean visible, boolean publicProductionRealm) { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5206,6 +5437,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( @@ -5238,6 +5470,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); @@ -5304,8 +5537,7 @@ void grantRealmAccessReactivatesRetainedTombstoneAndAdvancesItsVersion() { void getProfileReturnsDto() { Account account = new Account(); account.setId(2L); - retainAuthenticationIdentity(account); - when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); + setPersistedAuthenticationIdentity(account); Profile profile = new Profile(); profile.setAccount(account); profile.setTenantId(1L); @@ -5318,13 +5550,27 @@ void getProfileReturnsDto() { 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(AuthenticationException.class, () -> service.getProfile(1L, 2L)); + + verifyNoInteractions(notificationService); } @Test void profileProjectionRedactsRetainedLegacyPolicyWithoutRewritingEntity() { Account account = new Account(); account.setId(2L); - retainAuthenticationIdentity(account); + setPersistedAuthenticationIdentity(account); when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); Profile profile = new Profile(); profile.setAccount(account); @@ -5345,7 +5591,7 @@ void profileProjectionRedactsRetainedLegacyPolicyWithoutRewritingEntity() { void profileProjectionRereadsFullOwnerAndRejectsWrongOrUnavailableIdentity() { Account owner = new Account(); owner.setId(2L); - retainAuthenticationIdentity(owner); + setPersistedAuthenticationIdentity(owner); Account partial = new Account(); partial.setId(2L); Profile profile = profile(partial, 1L, "partial"); @@ -5385,8 +5631,7 @@ void updateProfileStoresChanges() { Profile profile = new Profile(); Account account = new Account(); account.setId(2L); - retainAuthenticationIdentity(account); - when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); + setPersistedAuthenticationIdentity(account); profile.setAccount(account); profile.setTenantId(1L); profile.setPresenceVisibilityPolicy(ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); @@ -5406,34 +5651,15 @@ void updateProfileStoresChanges() { assertEquals("demo", dto.displayName()); assertEquals(account.getAccountUuid().toString(), dto.accountId()); assertEquals(ProfilePresenceVisibilityPolicy.PRIVATE, profile.getPresenceVisibilityPolicy()); + org.mockito.Mockito.verify(profileRepository).findByAccountIdAndTenantId(2L, 1L); org.mockito.Mockito.verify(notificationService).sendNotification(1L, 2L, "Profile updated"); } - @Test - void updateProfileRejectsNumericRowSelectorBeforeReadingPrivateOwner() { - assertThrows( - IllegalArgumentException.class, - () -> - service.updateProfile( - new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( - 1L, "2", "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE))); - - verifyNoInteractions( - accountRepository, - accountTenantMembershipRepository, - profileRepository, - notificationService); - } - @Test void profileReadAndUpdateFailClosedWithoutCurrentTenantMembership() { - UUID accountUuid = UUID.randomUUID(); Account account = new Account(); account.setId(2L); - account.setAccountUuid(accountUuid); - account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); - account.setAccountUuidSourceNumericId(2L); - when(accountRepository.findByAccountUuid(accountUuid)).thenReturn(Optional.of(account)); + setPersistedAuthenticationIdentity(account); when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 1L)).thenReturn(false); assertEquals( @@ -5448,7 +5674,7 @@ void profileReadAndUpdateFailClosedWithoutCurrentTenantMembership() { service.updateProfile( new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( 1L, - accountUuid.toString(), + account.getAccountUuid().toString(), "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE))) @@ -5462,7 +5688,7 @@ void updateProfileRejectsReservedHiddenStaffPolicyBeforePersistence() { var request = new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( 1L, - UUID.randomUUID().toString(), + "d09f80cb-a46a-415e-8d35-c9e8068e49de", "demo", "bio", ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); @@ -5481,6 +5707,8 @@ 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"); @@ -6119,11 +6347,46 @@ void updateLoginAuthModesFailsClosedBeforeReadingOrPersistingAccount() { private Account directTextAccount() { Account account = new Account(); account.setId(11L); - retainAuthenticationIdentity(account); + 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, @@ -6200,14 +6463,6 @@ private static String playableStateNamespaceIdForTenant(long tenantId) { }; } - private void retainAuthenticationIdentity(Account account) { - account.setAccountUuid(UUID.randomUUID()); - account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); - account.setAccountUuidSourceNumericId(account.getId()); - when(accountRepository.findByAccountUuid(account.getAccountUuid())) - .thenReturn(Optional.of(account)); - } - private static AccountTenantMembership membership(Account account, long tenantId) { AccountTenantMembership membership = new AccountTenantMembership(); membership.setId(tenantId * 100 + (account.getId() == null ? 0L : account.getId())); diff --git a/services/common-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..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"); - requireText(accountId, "accountId"); + String canonicalAccountId = JwtClaims.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), @@ -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/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..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 @@ -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,71 @@ 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 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( + IllegalArgumentException.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"); + 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 +94,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 +117,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 +151,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 +164,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 +175,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 +185,7 @@ void requireGameplaySessionMatchRejectsMismatchedAttestedRoutingScope() { token, "22", "41", - "7", + ACCOUNT_UUID, "123", "1", "R-1021", @@ -129,12 +202,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 +219,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 +241,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 +254,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 +270,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 +283,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, "7", "123", "1", "R-1021")); + + assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); + 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", null, "0", "123", "1", "R-1021")); + service.requireGameplaySessionMatch( + token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); assertEquals("SESSION_ATTESTATION_INVALID", ex.getCode()); - assertEquals("Invalid claim: accountId", ex.getMessage()); + 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 +439,7 @@ void issueGameplaySessionAttestationRejectsLegacyRuntimeRoomId() { service.issueGameplaySessionAttestation( "22", "41", - "7", + ACCOUNT_UUID, "123", "1", "room-1021", @@ -371,7 +479,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 +503,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 +528,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 +551,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-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..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 @@ -4,15 +4,91 @@ 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 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"); + 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 +107,7 @@ void authenticationCanonicalizesMappedEmailAndMissingMembershipDeniesAdmission() .setPassword("password") .build()) .getAccountId()) - .isEqualTo("7"); + .isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(7L)); server.setMembershipExists(false); @@ -58,11 +134,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 +152,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 +164,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 +185,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 +202,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 +225,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 5acefe50ce..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 @@ -5,9 +5,11 @@ 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; @@ -41,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", @@ -53,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); @@ -62,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(); } @@ -97,6 +106,7 @@ public static String accountUuidForTestFixture(long accountId) { 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) { @@ -148,6 +158,10 @@ public void resetRuntimeState() { allowPublicJoin.set(true); realmAccessGranted.set(true); profilesByAccountId.clear(); + accountIdsByUuid.clear(); + accountIdsByEmail + .values() + .forEach(id -> accountIdsByUuid.put(accountUuidForTestFixture(id), id)); connectScopesById.clear(); } @@ -164,9 +178,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(); @@ -186,7 +202,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(); } @@ -203,7 +219,7 @@ public void getRealmAccessGrantForRuntime( .setRealmSlug(request.getRealmSlug()) .setGranted(realmAccessGranted.get()) .setGrantVersion(1L) - .setEvaluatedAt(EVALUATED_AT) + .setEvaluatedAt(clock.instant().toString()) .build()); responseObserver.onCompleted(); } @@ -219,7 +235,7 @@ public void getTenantEntitlementsForRuntime( .setAllowPublicJoin(allowPublicJoin.get()) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt(EVALUATED_AT) + .setEvaluatedAt(clock.instant().toString()) .build()); responseObserver.onCompleted(); } @@ -263,7 +279,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( @@ -307,7 +323,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()) @@ -349,7 +365,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( @@ -370,7 +394,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 = @@ -391,6 +423,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/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/mapper/CharacterMapper.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java index 5f90995c33..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) @@ -15,7 +16,8 @@ public interface CharacterMapper { @Mapping(target = "playableStateKey", ignore = true) @Mapping(target = "bodyLayoutKey", constant = "DEFAULT") @Mapping(target = "actorIdentity", ignore = true) - @Mapping(target = "accountUuid", 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/CharacterRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java index 08542372a0..8d34f302f3 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 @@ -256,28 +256,6 @@ public Page findByTenantIdAndAccountUuidAndPlayableStateKey( : new PageImpl<>(content, pageable, total); } - public Page findByTenantIdAndAccountIdAndPlayableStateKey( - Long tenantId, Long accountId, String playableStateKey, Pageable pageable) { - var condition = - CHARACTERS - .TENANT_ID - .eq(tenantId) - .and(CHARACTERS.ACCOUNT_ID.eq(accountId)) - .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey)) - .and(legacyCharacterRow()); - long total = dsl.fetchCount(CHARACTERS, condition); - var content = - dsl.selectFrom(CHARACTERS) - .where(condition) - .orderBy(CHARACTERS.ID.asc()) - .limit(limitOrDefault(pageable, Integer.MAX_VALUE)) - .offset(offsetOrZero(pageable)) - .fetch(this::toEntity); - return pageable == null || pageable.isUnpaged() - ? new PageImpl<>(content) - : new PageImpl<>(content, pageable, total); - } - public Optional findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( Long tenantId, String playableStateKey, String name) { return Optional.ofNullable( 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..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 @@ -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; @@ -51,13 +52,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)); @@ -79,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; @@ -136,12 +145,13 @@ 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( + .findByTenantIdAndAccountUuidAndPlayableStateKey( tenantId, accountId, playableStateKeyResolver.resolve(gameInstanceId, playableStateScope), @@ -165,7 +175,17 @@ 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) { + 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/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/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 5547fb6299..abb4d98886 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()); @@ -153,6 +182,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()); @@ -217,4 +247,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(); + } } 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 82f4d8bbca..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,8 +1067,8 @@ private void assertNumericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAn canonicalCharacterId, entityTenantRowId, namespaceUuid.toString())) .isEmpty(); assertThat( - characterRepository.findByTenantIdAndAccountIdAndPlayableStateKey( - entityTenantRowId, 23L, namespaceUuid.toString(), Pageable.unpaged())) + characterRepository.findByTenantIdAndAccountUuidAndPlayableStateKey( + entityTenantRowId, accountUuid, namespaceUuid.toString(), Pageable.unpaged())) .isEmpty(); assertThat( characterRepository.findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( @@ -1097,9 +1097,11 @@ private void assertNumericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAn assertThat(characterRepository.findByIdAndTenantId(legacyCharacterId, entityTenantRowId)) .isPresent(); assertThat( - characterRepository.findByTenantIdAndAccountIdAndPlayableStateKey( - entityTenantRowId, 23L, "shared-live", Pageable.unpaged())) - .hasSize(1); + characterRepository.findByTenantIdAndAccountUuidAndPlayableStateKey( + 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 4fb07a812d..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,11 +127,10 @@ void legacySaveAllocatesQuarantinedUuidAndPreservesLegacyReadbackAndUpdates() { .isPresent(); assertThat( characterRepository - .findByTenantIdAndAccountIdAndPlayableStateKey( - tenantId, accountId, actor.getPlayableStateKey(), null) + .findByTenantIdAndAccountUuidAndPlayableStateKey( + tenantId, accountUuid, actor.getPlayableStateKey(), null) .getContent()) - .extracting(Character::getId) - .containsExactly(actorId); + .isEmpty(); assertThat( characterRepository.findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( tenantId, actor.getPlayableStateKey(), "retained ACTOR")) 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..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 @@ -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())) + when(repo.findByTenantIdAndAccountUuidAndPlayableStateKey( + 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()); + .findByTenantIdAndAccountUuidAndPlayableStateKey( + 1L, OWNER, "shared-live", Pageable.unpaged()); } @Test @@ -72,15 +78,16 @@ void listForTenantAndAccountDoesNotCrossTenantBoundary() { new ScopedCharacterResolver(repo, new PlayableStateKeyResolver())); service.initMetrics(); - when(repo.findByTenantIdAndAccountIdAndPlayableStateKey( - 2L, 1L, "instance:91", Pageable.unpaged())) + when(repo.findByTenantIdAndAccountUuidAndPlayableStateKey( + 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()); + .findByTenantIdAndAccountUuidAndPlayableStateKey( + 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 c1a8bd9b14..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 @@ -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; @@ -16,9 +20,149 @@ 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(IllegalStateException.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() { + 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(IllegalStateException.class, () -> service.getWithInventory(1L)); + assertThrows( + IllegalStateException.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 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() { 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()); 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/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/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..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 @@ -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; @@ -56,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; @@ -381,11 +384,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 +749,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 +769,36 @@ 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; + } + return isSafeAuthorityReplyEvaluation(response.getEvaluatedAt()); + } + + private static boolean isSafeAuthorityReplyEvaluation(String evaluatedAt) { + try { + 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, @@ -918,9 +964,12 @@ private boolean isSafeMembershipAuthorityResponse( return false; } try { - Instant.parse(response.getEvaluatedAt()); - if (!PositiveLongParsing.requireOptionalText(response.getAccountId(), "accountId") - .equals(PositiveLongParsing.requireOptionalText(context.accountId(), "accountId")) + if (!isSafeAuthorityReplyEvaluation(response.getEvaluatedAt())) { + return false; + } + 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/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 d4a9279373..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 @@ -5,7 +5,6 @@ import java.util.Objects; import java.util.Optional; import net.firedevops.firemud.common.security.JwtClaims; -import org.springframework.util.StringUtils; /** Represents persisted login context stored in Redis for a session. */ public record SessionContext( @@ -337,7 +336,7 @@ public static boolean isCanonicalAccountIdentity(String accountId) { } 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/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/RedisFirstPartyConnectContextRegistry.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java index 61deba6f1e..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; @@ -81,11 +85,18 @@ 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. + LOG.warn( + "Retained first-party connect context kept for session {}: {}", + sessionId, + ex.getClass().getSimpleName()); } } 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 a075cb6335..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 @@ -9,16 +9,17 @@ import java.util.EnumMap; import java.util.List; import java.util.Map; -import net.firedevops.firemud.cache.ScreenBufferService; -import net.firedevops.firemud.gamesession.service.SessionContextService; import net.firedevops.firemud.gamesession.test.ChatTestFixtures; import net.firedevops.firemud.gamesession.testsupport.GameplayAsyncAssertions; import net.firedevops.firemud.gamesession.testsupport.GameplayCrossServiceStack; import net.firedevops.firemud.gamesession.testsupport.GameplayEntityAssertions; +import net.firedevops.firemud.gamesession.testsupport.GameplaySocialAssertions; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketDriver; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketScenarios; +import net.firedevops.firemud.socialgroups.v1.ChatType; 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; @@ -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"; @@ -85,201 +90,211 @@ static synchronized void stopServices() { } @Test - void websocketNumericSayRefusesWithoutSocialWriteAndReportsMetrics() throws Exception { + void websocketSayFlowReportsCanonicalTranscriptAndMetrics() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); List responses = runCommunicationSequence( - sessionId, "SAY hello travelers", "ERROR COMMUNICATION_NOT_DELIVERED"); + sessionId, "SAY hello travelers", ChatTestFixtures.canonicalSayText()); + assertThat(responses).hasSizeGreaterThanOrEqualTo(3); assertThat(responses).anyMatch(response -> response.startsWith("OK LOGIN")); assertThat(responses).anyMatch(response -> response.startsWith("OK PLAY")); assertThat(responses) - .anyMatch( - response -> - response.contains( - "ERROR COMMUNICATION_NOT_DELIVERED Sender Account identity unavailable")); - assertThat(socialStub().messageRequests()).isEmpty(); + .anyMatch(response -> response.contains(ChatTestFixtures.canonicalSayText())); + 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); + assertThat(request.getEffectId()).isNotBlank(); + }); + GameplayAsyncAssertions.assertMetricEventually( gameSession().bean(io.micrometer.core.instrument.MeterRegistry.class), COMMAND_WAIT, "gamesession.command.say.invocations", 1.0); - GameplayAsyncAssertions.assertMetricEventually( - gameSession().bean(io.micrometer.core.instrument.MeterRegistry.class), - COMMAND_WAIT, - "gamesession.command.say.failures", - 1.0, - "error", - "INVALID_ARGUMENT"); } @Test - void websocketNumericSayDoesNotWriteLiveRoomListenerView() throws Exception { + void websocketSayPushesRoomListenerViewToLiveRecipient() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); + try (GameplayWebSocketScenarios.TwoPlayerScenario scenario = GameplayWebSocketScenarios.openReadyPair( GameplayWebSocketScenarios.proxyGatewayDriverFactory( gameSessionWebSocketUrl(), COMMAND_WAIT, TENANT_ID, sessionId), - "numeric-actor-conn", + "actor-say-conn", GameplayWebSocketScenarios.demoAdmission("Emberline", READY_LOOK_TEXT), - "numeric-target-conn", + "target-say-conn", GameplayWebSocketScenarios.demoAdmission( "sora@example.com", "Sora", READY_LOOK_TEXT))) { - var target = - gameSession() - .bean(SessionContextService.class) - .findByGameplayName(TENANT_ID, DEMO_WORLD_INSTANCE_ID, "Sora") - .orElseThrow(); - ScreenBufferService buffers = gameSession().bean(ScreenBufferService.class); - var before = buffers.get(target.tenantId(), target.gameInstanceId(), target.characterId()); - int cursor = scenario.actor().responseCount(); scenario.actor().send("SAY hello travelers"); - assertThat( - scenario - .actor() - .awaitTranscriptContainingAllAfter( - cursor, - "ERROR COMMUNICATION_NOT_DELIVERED", - "Sender Account identity unavailable")) - .contains("ERROR COMMUNICATION_NOT_DELIVERED"); - assertThat(socialStub().messageRequests()).isEmpty(); - assertThat(buffers.get(target.tenantId(), target.gameInstanceId(), target.characterId())) - .isEqualTo(before); + scenario.actor().awaitContains(ChatTestFixtures.canonicalSayText()); + scenario.target().awaitContains(ChatTestFixtures.canonicalSayListenerText()); } } @Test - void websocketNumericWhisperRefusesWithoutSocialWriteAndReportsMetrics() throws Exception { + void websocketWhisperFlowReportsCanonicalTranscriptAndMetadata() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); List responses = runCommunicationSequence( - sessionId, "WHISPER Sora keep quiet", "ERROR COMMUNICATION_NOT_DELIVERED"); + sessionId, "WHISPER Sora keep quiet", ChatTestFixtures.canonicalWhisperText()); + assertThat(responses).hasSizeGreaterThanOrEqualTo(3); - assertThat(responses).anyMatch(response -> response.startsWith("OK LOGIN")); - assertThat(responses).anyMatch(response -> response.startsWith("OK PLAY")); assertThat(responses) - .anyMatch( - response -> - response.contains( - "ERROR COMMUNICATION_NOT_DELIVERED Sender Account identity unavailable")); - assertThat(socialStub().messageRequests()).isEmpty(); + .anyMatch(response -> response.contains(ChatTestFixtures.canonicalWhisperText())); + GameplayEntityAssertions.assertMessage( + socialStub().lastRequest(), + ChatType.CHAT_TYPE_WHISPER, + 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), COMMAND_WAIT, "gamesession.command.whisper.invocations", 1.0); - GameplayAsyncAssertions.assertMetricEventually( - gameSession().bean(io.micrometer.core.instrument.MeterRegistry.class), - COMMAND_WAIT, - "gamesession.command.whisper.failures", - 1.0, - "error", - "INVALID_ARGUMENT"); } @Test - void websocketNumericTellRefusesWithoutSocialOrTargetWritesAndReportsMetrics() throws Exception { + void websocketTellFlowReportsCanonicalTranscriptAndMetadata() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); seedLiveTargetSession(); - var target = - gameSession() - .bean(SessionContextService.class) - .findByGameplayName(TENANT_ID, DEMO_WORLD_INSTANCE_ID, "Sora") - .orElseThrow(); - ScreenBufferService buffers = gameSession().bean(ScreenBufferService.class); - var targetBefore = - buffers.get(target.tenantId(), target.gameInstanceId(), target.characterId()); List responses = runCommunicationSequence( - sessionId, "TELL Sora meet me at the forge", "ERROR COMMUNICATION_NOT_DELIVERED"); + sessionId, "TELL Sora meet me at the forge", ChatTestFixtures.canonicalTellText()); + assertThat(responses).hasSizeGreaterThanOrEqualTo(3); - assertThat(responses).anyMatch(response -> response.startsWith("OK LOGIN")); - assertThat(responses).anyMatch(response -> response.startsWith("OK PLAY")); assertThat(responses) - .anyMatch( - response -> - response.contains( - "ERROR COMMUNICATION_NOT_DELIVERED Sender Account identity unavailable")); - assertThat(socialStub().messageRequests()).isEmpty(); - assertThat(buffers.get(target.tenantId(), target.gameInstanceId(), target.characterId())) - .isEqualTo(targetBefore); + .anyMatch(response -> response.contains(ChatTestFixtures.canonicalTellText())); + GameplayEntityAssertions.assertMessage( + socialStub().lastRequest(), + ChatType.CHAT_TYPE_TELL, + 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), COMMAND_WAIT, "gamesession.command.tell.invocations", 1.0); - GameplayAsyncAssertions.assertMetricEventually( - gameSession().bean(io.micrometer.core.instrument.MeterRegistry.class), - COMMAND_WAIT, - "gamesession.command.tell.failures", - 1.0, - "error", - "INVALID_ARGUMENT"); } @Test - void websocketNumericFriendsReadRefusesBeforeSocial() throws Exception { + void websocketFriendsShowsCanonicalCrossGamePresence() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); - try (GameplayWebSocketDriver client = - openReadySessionClient(sessionId, "numeric-friend-conn")) { - client.send("FRIENDS"); - client.awaitContains("ERROR FRIEND_PRESENCE_UNAVAILABLE"); - assertNoFriendRequests(); - } + + List responses = + runCommunicationSequence( + sessionId, + "FRIENDS", + "Sora [acct #" + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)"); + + assertThat(responses).hasSizeGreaterThanOrEqualTo(3); + assertThat(responses) + .anyMatch( + response -> + response.contains( + "Sora [acct #" + + SORA_ACCOUNT_UUID + + "] - online in Demo World / Live Realm (idle)")); + GameplaySocialAssertions.assertListFriendsRequest( + socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); } @Test - void websocketNumericOnlineFriendsReadRefusesBeforeSocial() throws Exception { + void websocketFriendsOnlineFiltersCanonicalRoster() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); - try (GameplayWebSocketDriver client = - openReadySessionClient(sessionId, "numeric-friend-conn")) { - client.send("FRIENDS ONLINE"); - client.awaitContains("ERROR FRIEND_PRESENCE_UNAVAILABLE"); - assertNoFriendRequests(); - } + + List responses = + runCommunicationSequence( + sessionId, + "FRIENDS ONLINE", + "Friends ONLINE [1/1]:\n" + + "1) Sora [acct #" + + SORA_ACCOUNT_UUID + + "] - online in Demo World / Live Realm (idle)"); + + assertThat(responses) + .anyMatch( + response -> + response.contains("Friends ONLINE [1/1]:") + && response.contains( + "1) Sora [acct #" + + SORA_ACCOUNT_UUID + + "] - online in Demo World / Live Realm (idle)")); + GameplaySocialAssertions.assertListFriendsRequest( + socialStub().lastFriendsRequest(), + Long.toString(TENANT_ID), + ACCOUNT_UUID, + net.firedevops.firemud.socialgroups.v1.FriendRosterFilter.FRIEND_ROSTER_FILTER_ONLINE); } @Test - void websocketNumericSharedFriendsReadRefusesBeforeSocial() throws Exception { + void websocketFriendsSharedFiltersCanonicalRoster() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); - try (GameplayWebSocketDriver client = - openReadySessionClient(sessionId, "numeric-friend-conn")) { - client.send("FRIENDS SHARED"); - client.awaitContains("ERROR FRIEND_PRESENCE_UNAVAILABLE"); - assertNoFriendRequests(); - } + + List responses = + runCommunicationSequence( + sessionId, + "FRIENDS SHARED", + "Friends SHARED [1/1]:\n" + + "1) Sora [acct #" + + SORA_ACCOUNT_UUID + + "] - online in Demo World / Live Realm (idle)"); + + assertThat(responses) + .anyMatch( + response -> + response.contains("Friends SHARED [1/1]:") + && response.contains( + "1) Sora [acct #" + + SORA_ACCOUNT_UUID + + "] - online in Demo World / Live Realm (idle)")); + GameplaySocialAssertions.assertListFriendsRequest( + socialStub().lastFriendsRequest(), + Long.toString(TENANT_ID), + ACCOUNT_UUID, + net.firedevops.firemud.socialgroups.v1.FriendRosterFilter.FRIEND_ROSTER_FILTER_SHARED); } @Test - void freshGameplayBaselineRestoresFixturePresenceWhileNumericPlayerReadRefuses() - throws Exception { + void freshGameplayBaselineReappliesConfiguredFriendPresenceBaseline() throws Exception { ensureTestServicesStarted(); - prepareGameInstance(); - var client = - gameSession().bean(net.firedevops.firemud.gamesession.client.SocialGroupsClient.class); - String fixtureAccount = AccountRuntimeStubServer.accountUuidForTestFixture(ACCOUNT_ID); - socialStub().setFriendPresenceEntries(List.of()); - assertThat(client.listFriendPresence(TENANT_ID, fixtureAccount).getPresencesList()).isEmpty(); long sessionId = prepareGameInstance(); - var restored = client.listFriendPresence(TENANT_ID, fixtureAccount); - assertThat(restored.getPresencesCount()).isEqualTo(1); - assertThat(restored.getPresences(0).getFriendAccountId()) - .isEqualTo(Long.toString(SORA_ACCOUNT_ID)); - assertThat(restored.getPresences(0).getCharacterName()).isEqualTo("Sora"); - var priorPresenceRead = socialStub().lastPresenceRequest(); + socialStub().setFriendPresenceEntries(List.of()); + + sessionId = prepareGameInstance(); List responses = - runCommunicationSequence(sessionId, "FRIENDS", "ERROR FRIEND_PRESENCE_UNAVAILABLE"); + runCommunicationSequence( + sessionId, + "FRIENDS", + "Sora [acct #" + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)"); + assertThat(responses) - .anyMatch(response -> response.contains("ERROR FRIEND_PRESENCE_UNAVAILABLE")); - assertThat(socialStub().lastPresenceRequest()).isEqualTo(priorPresenceRead); - assertNoFriendRequests(); + .anyMatch( + response -> + response.contains( + "Sora [acct #" + + SORA_ACCOUNT_UUID + + "] - online in Demo World / Live Realm (idle)")); } @Test @@ -316,208 +331,258 @@ void freshGameplayBaselineRestoresAlwaysEnabledTruncateGuards() throws Exception } @Test - void websocketNumericFriendMutationsRefuseBeforeSocial() throws Exception { + void websocketFriendsMutationFlowUsesCanonicalRosterSurface() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); + try (GameplayWebSocketDriver client = - openReadySessionClient(sessionId, "numeric-friend-conn")) { - client.send("FRIENDS ADD 77"); - client.awaitContains("ERROR FRIEND_ADD_UNAVAILABLE"); - assertNoFriendRequests(); - client.send("FRIENDS REMOVE 77"); - client.awaitContains("ERROR FRIEND_REMOVE_UNAVAILABLE"); - assertNoFriendRequests(); + openReadySessionClient(sessionId, "friends-mutate-conn")) { + 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), + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); + GameplaySocialAssertions.assertRemoveFriendRequest( + socialStub().lastRemoveFriendRequest(), + Long.toString(TENANT_ID), + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); } @Test - void websocketNumericFriendNameMutationsRefuseBeforeSocial() throws Exception { + void websocketFriendsMutationByCharacterNameUsesCanonicalIdentityLookup() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); + try (GameplayWebSocketDriver client = - openReadySessionClient(sessionId, "numeric-friend-conn")) { + openReadySessionClient(sessionId, "friends-mutate-name-conn")) { client.send("FRIENDS ADD Sora"); - client.awaitContains("ERROR FRIEND_ADD_UNAVAILABLE"); - assertNoFriendRequests(); + client.awaitContains("Sora [acct #" + SORA_ACCOUNT_UUID + "] added."); client.send("FRIENDS REMOVE Sora"); - client.awaitContains("ERROR FRIEND_REMOVE_UNAVAILABLE"); - assertNoFriendRequests(); + client.awaitContains("Sora [acct #" + SORA_ACCOUNT_UUID + "] removed."); } + + GameplaySocialAssertions.assertAddFriendRequest( + socialStub().lastAddFriendRequest(), + Long.toString(TENANT_ID), + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); + GameplaySocialAssertions.assertRemoveFriendRequest( + socialStub().lastRemoveFriendRequest(), + Long.toString(TENANT_ID), + ACCOUNT_UUID, + SORA_ACCOUNT_UUID); } @Test - void websocketNumericFriendOrdinalRemovalRefusesBeforeSocial() throws Exception { + void websocketFriendsRemoveByRosterOrdinalUsesRenderedRosterIdentity() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); + try (GameplayWebSocketDriver client = - openReadySessionClient(sessionId, "numeric-friend-conn")) { + openReadySessionClient(sessionId, "friends-remove-ordinal-conn")) { client.send("FRIENDS REMOVE #1"); - client.awaitContains("ERROR FRIEND_REMOVE_UNAVAILABLE"); - assertNoFriendRequests(); + client.awaitContains("Sora [acct #" + SORA_ACCOUNT_UUID + "] removed."); } + + GameplaySocialAssertions.assertRemoveFriendByOrdinalRequest( + socialStub().lastRemoveFriendByOrdinalRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID, 1); } @Test - void websocketNumericFriendDetailRefusesBeforeSocial() throws Exception { + void websocketFriendsShowUsesCanonicalFriendDetailSurface() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); + try (GameplayWebSocketDriver client = - openReadySessionClient(sessionId, "numeric-friend-conn")) { + openReadySessionClient(sessionId, "friends-show-detail-conn")) { client.send("FRIENDS SHOW #1"); - client.awaitContains("ERROR FRIEND_DETAIL_UNAVAILABLE"); - assertNoFriendRequests(); + 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), ACCOUNT_UUID, 1); } @Test - void websocketNumericFriendSummaryRefusesBeforeSocial() throws Exception { + void websocketFriendsSummaryUsesCanonicalRosterSummarySurface() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); + try (GameplayWebSocketDriver client = - openReadySessionClient(sessionId, "numeric-friend-conn")) { + openReadySessionClient(sessionId, "friends-summary-conn")) { client.send("FRIENDS SUMMARY"); - client.awaitContains("ERROR FRIEND_SUMMARY_UNAVAILABLE"); - assertNoFriendRequests(); + client.awaitContains("Friend roster summary:"); + client.awaitContains("Linked: 1"); + client.awaitContains("Online: 1"); + client.awaitContains("Offline: 0"); + client.awaitContains("Recent offline: 0"); } + + GameplaySocialAssertions.assertFriendRosterSummaryRequest( + socialStub().lastSummaryRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); } @Test - void websocketNumericVisibilityReadAndUpdateRefuseBeforeSocial() throws Exception { + void websocketFriendsVisibilityShowsCurrentPolicy() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); + try (GameplayWebSocketDriver client = - openReadySessionClient(sessionId, "numeric-friend-conn")) { + openReadySessionClient(sessionId, "friends-visibility-conn")) { client.send("FRIENDS VISIBILITY"); - client.awaitContains("ERROR FRIEND_VISIBILITY_UNAVAILABLE"); - assertNoFriendRequests(); + client.awaitContains("Friend presence visibility: FRIENDS_ONLY"); client.send("FRIENDS VISIBILITY PRIVATE"); - client.awaitContains("ERROR FRIEND_VISIBILITY_UPDATE_UNAVAILABLE"); - assertNoFriendRequests(); + client.awaitContains("Friend presence visibility set to PRIVATE."); + client.awaitContains("Friend presence visibility: PRIVATE"); } + + GameplaySocialAssertions.assertGetVisibilityRequest( + socialStub().lastGetVisibilityRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); + GameplaySocialAssertions.assertUpdateVisibilityRequest( + socialStub().lastUpdateVisibilityRequest(), + Long.toString(TENANT_ID), + ACCOUNT_UUID, + FriendPresenceVisibilityPolicy.FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); } @Test - void websocketNumericWhisperDoesNotWriteLiveTargetOrObserverViews() throws Exception { + void websocketWhisperPushesTargetAndObserverViewsToLiveRecipients() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); + try (GameplayWebSocketScenarios.ThreePlayerScenario scenario = GameplayWebSocketScenarios.openReadyTrio( GameplayWebSocketScenarios.proxyGatewayDriverFactory( gameSessionWebSocketUrl(), COMMAND_WAIT, TENANT_ID, sessionId), - "numeric-actor-conn", + "actor-conn", GameplayWebSocketScenarios.demoAdmission("Emberline", READY_LOOK_TEXT), - "numeric-target-conn", + "target-conn", GameplayWebSocketScenarios.demoAdmission("sora@example.com", "Sora", READY_LOOK_TEXT), - "numeric-observer-conn", + "observer-conn", GameplayWebSocketScenarios.demoAdmission("nyx@example.com", "Nyx", READY_LOOK_TEXT))) { - var contexts = gameSession().bean(SessionContextService.class); - var target = - contexts.findByGameplayName(TENANT_ID, DEMO_WORLD_INSTANCE_ID, "Sora").orElseThrow(); - var observer = - contexts.findByGameplayName(TENANT_ID, DEMO_WORLD_INSTANCE_ID, "Nyx").orElseThrow(); - ScreenBufferService buffers = gameSession().bean(ScreenBufferService.class); - var targetBefore = - buffers.get(target.tenantId(), target.gameInstanceId(), target.characterId()); - var observerBefore = - buffers.get(observer.tenantId(), observer.gameInstanceId(), observer.characterId()); - int cursor = scenario.actor().responseCount(); scenario.actor().send("WHISPER Sora Keep quiet"); - assertThat( - scenario - .actor() - .awaitTranscriptContainingAllAfter( - cursor, - "ERROR COMMUNICATION_NOT_DELIVERED", - "Sender Account identity unavailable")) - .contains("ERROR COMMUNICATION_NOT_DELIVERED"); - assertThat(socialStub().messageRequests()).isEmpty(); - assertThat(buffers.get(target.tenantId(), target.gameInstanceId(), target.characterId())) - .isEqualTo(targetBefore); - assertThat( - buffers.get(observer.tenantId(), observer.gameInstanceId(), observer.characterId())) - .isEqualTo(observerBefore); + scenario.actor().awaitContains(ChatTestFixtures.canonicalWhisperText()); + scenario.target().awaitContains(ChatTestFixtures.canonicalWhisperTargetText()); + scenario.observer().awaitContains(ChatTestFixtures.canonicalWhisperObserverMetadataText()); } } @Test - void websocketNumericTellDoesNotWriteLiveTargetView() throws Exception { + void websocketTellPushesTargetViewToLiveRecipient() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); + try (GameplayWebSocketScenarios.TwoPlayerScenario scenario = GameplayWebSocketScenarios.openReadyPair( GameplayWebSocketScenarios.proxyGatewayDriverFactory( gameSessionWebSocketUrl(), COMMAND_WAIT, TENANT_ID, sessionId), - "numeric-actor-conn", + "actor-tell-conn", GameplayWebSocketScenarios.demoAdmission("Emberline", READY_LOOK_TEXT), - "numeric-target-conn", + "target-tell-conn", GameplayWebSocketScenarios.demoAdmission( "sora@example.com", "Sora", READY_LOOK_TEXT))) { - var target = - gameSession() - .bean(SessionContextService.class) - .findByGameplayName(TENANT_ID, DEMO_WORLD_INSTANCE_ID, "Sora") - .orElseThrow(); - ScreenBufferService buffers = gameSession().bean(ScreenBufferService.class); - var before = buffers.get(target.tenantId(), target.gameInstanceId(), target.characterId()); - int cursor = scenario.actor().responseCount(); scenario.actor().send("TELL Sora Meet me at the forge"); - assertThat( - scenario - .actor() - .awaitTranscriptContainingAllAfter( - cursor, - "ERROR COMMUNICATION_NOT_DELIVERED", - "Sender Account identity unavailable")) - .contains("ERROR COMMUNICATION_NOT_DELIVERED"); - assertThat(socialStub().messageRequests()).isEmpty(); - assertThat(buffers.get(target.tenantId(), target.gameInstanceId(), target.characterId())) - .isEqualTo(before); + scenario.actor().awaitContains(ChatTestFixtures.canonicalTellText()); + scenario.target().awaitContains(ChatTestFixtures.canonicalTellTargetText()); } } @Test - void websocketNumericItemMutationsRefuseWithoutChangingInventoryOrContainers() throws Exception { + void websocketItemLoopMovesRoomItemThroughInventoryAndBack() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); - try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "numeric-item-conn")) { - int cursor = client.responseCount(); + + try (GameplayWebSocketDriver client = openReadySessionClient(sessionId, "item-loop-conn")) { + client.send("INV HERE"); + client.awaitContains("Room Inventory:"); + client.awaitContains("- Torch [torch#1] (A small torch)"); + client.awaitContains("- Backpack [backpack#1] (A weathered backpack)"); + + int pickupResponseCount = client.responseCount(); + client.send("GET Torch"); assertThat( client.awaitTranscriptContainingAllAfter( - cursor, "Room Inventory:", "Torch", "Backpack")) - .contains("Torch", "Backpack"); - cursor = client.responseCount(); - client.send("INV"); + pickupResponseCount, + "You pick up Torch.", + "Inventory:", + "- Torch [torch#1] (A small torch)", + "Room Inventory:", + "- Backpack [backpack#1] (A weathered backpack)")) + .contains("Room Inventory:"); + GameplayEntityAssertions.assertPickup( + entityStub().lastPickupRequest(), + String.valueOf(TENANT_ID), + ChatTestFixtures.PLAYER_EMBERLINE, + String.valueOf(DEMO_WORLD_INSTANCE_ID), + ChatTestFixtures.ROOM_ID, + "torch"); + + int containerResponseCount = client.responseCount(); + client.send("CONTAINER Backpack"); + client.awaitTranscriptContainingAllAfter( + containerResponseCount, + "Container: Backpack [backpack#1]", + "- Ration [ration#1] (A dry trail ration)"); + + int putResponseCount = client.responseCount(); + client.send("PUT Torch INTO Backpack"); + client.awaitTranscriptContainingAllAfter( + putResponseCount, "You put Torch into Backpack.", "- Torch [torch#1] (A small torch)"); + GameplayEntityAssertions.assertPut( + entityStub().lastPutRequest(), + String.valueOf(TENANT_ID), + ChatTestFixtures.PLAYER_EMBERLINE, + "container-backpack-1", + "torch", + "torch-ground-1"); + + int takeResponseCount = client.responseCount(); + client.send("TAKE Torch FROM Backpack"); + client.awaitTranscriptContainingAllAfter( + takeResponseCount, + "You take Torch from Backpack.", + "- Ration [ration#1] (A dry trail ration)"); + GameplayEntityAssertions.assertTake( + entityStub().lastTakeRequest(), + String.valueOf(TENANT_ID), + ChatTestFixtures.PLAYER_EMBERLINE, + "container-backpack-1", + "torch", + ""); + + int dropResponseCount = client.responseCount(); + client.send("DROP Torch"); assertThat( client.awaitTranscriptContainingAllAfter( - cursor, "Inventory:", "Leather Cap", "Iron Boots")) - .doesNotContain("Torch"); - for (String command : List.of("GET Torch", "DROP Leather Cap")) { - cursor = client.responseCount(); - client.send(command); - assertThat(client.awaitTranscriptContainingAllAfter(cursor, "ERROR INVENTORY_UNAVAILABLE")) - .contains("ERROR INVENTORY_UNAVAILABLE"); - assertThat(entityStub().lastPickupRequest()).isEmpty(); - assertThat(entityStub().lastDropRequest()).isEmpty(); - assertThat(entityStub().lastPutRequest()).isEmpty(); - assertThat(entityStub().lastTakeRequest()).isEmpty(); - } - cursor = client.responseCount(); + dropResponseCount, + "You drop Torch.", + "Inventory:", + "- Leather Cap [cap#1] (A small cap)", + "- Iron Boots [boots#1] (Heavy iron boots)", + "Room Inventory:", + "- Torch [torch#1] (A small torch)")) + .contains("Room Inventory:"); + int finalInventoryCount = client.responseCount(); client.send("INV HERE"); - assertThat( - client.awaitTranscriptContainingAllAfter( - cursor, "Room Inventory:", "Torch", "Backpack")) - .contains("Torch", "Backpack"); - cursor = client.responseCount(); - client.send("INV"); - assertThat( - client.awaitTranscriptContainingAllAfter( - cursor, "Inventory:", "Leather Cap", "Iron Boots")) - .doesNotContain("Torch"); - cursor = client.responseCount(); - client.send("CONTAINER Backpack"); - assertThat(client.awaitTranscriptContainingAllAfter(cursor, "Container: Backpack", "Ration")) - .doesNotContain("Torch"); + client.awaitTranscriptContainingAllAfter( + finalInventoryCount, "Room Inventory:", "- Torch [torch#1] (A small torch)"); + GameplayEntityAssertions.assertDrop( + entityStub().lastDropRequest(), + String.valueOf(TENANT_ID), + ChatTestFixtures.PLAYER_EMBERLINE, + String.valueOf(DEMO_WORLD_INSTANCE_ID), + ChatTestFixtures.ROOM_ID, + "torch"); } } @@ -567,18 +632,6 @@ void websocketEquipmentLoopMovesCarriedItemThroughSlotAndBack() throws Exception } } - private static void assertNoFriendRequests() { - assertThat(socialStub().lastFriendsRequest()).isEmpty(); - assertThat(socialStub().lastAddFriendRequest()).isEmpty(); - assertThat(socialStub().lastRemoveFriendRequest()).isEmpty(); - assertThat(socialStub().lastGetFriendRequest()).isEmpty(); - assertThat(socialStub().lastGetFriendByOrdinalRequest()).isEmpty(); - assertThat(socialStub().lastRemoveFriendByOrdinalRequest()).isEmpty(); - assertThat(socialStub().lastSummaryRequest()).isEmpty(); - assertThat(socialStub().lastGetVisibilityRequest()).isEmpty(); - assertThat(socialStub().lastUpdateVisibilityRequest()).isEmpty(); - } - private static synchronized void ensureTestServicesStarted() throws Exception { if (STACK == null) { STACK = @@ -591,7 +644,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/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java index d8a21e087f..38927c2195 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java @@ -177,7 +177,7 @@ void tenConcurrentPlayersCanMoveNorthAfterConcurrentEntry() throws Exception { } @Test - void tenConcurrentNumericPlayersRefuseSayWithoutDeliveryAfterConcurrentEntry() throws Exception { + void tenConcurrentPlayersCanBroadcastSayAfterConcurrentEntry() throws Exception { ensureTestServicesStarted(); List players = GameplayLoadScenarios.seedPlayers(STACK, TENANT_ID, 1L, ACCOUNT_ID_BASE, CLIENT_COUNT, 7L); @@ -196,55 +196,36 @@ void tenConcurrentNumericPlayersRefuseSayWithoutDeliveryAfterConcurrentEntry() t return null; }); assertCompletesWithin( - "concurrent numeric SAY refusal burst", followUp.duration(), FOLLOW_UP_PHASE_BUDGET); + "concurrent SAY broadcast burst", followUp.duration(), FOLLOW_UP_PHASE_BUDGET); connectedPlayers.forEach( - connectedPlayer -> { - assertThat(connectedPlayer.driver().responses()) - .anyMatch( - payload -> - payload.contains( - "ERROR COMMUNICATION_NOT_DELIVERED Sender Account identity unavailable")); - assertThat(connectedPlayer.driver().responses()) - .noneMatch( - payload -> - payload.startsWith("ERROR ") - && !payload.contains("ERROR COMMUNICATION_NOT_DELIVERED")); - assertThat(connectedPlayer.driver().responses()) - .noneMatch( - payload -> - payload.contains(expectedSayTranscript(connectedPlayer.player())) - || payload.contains("Multiplayer burst ")); - var context = - gameSession() - .bean(SessionContextService.class) - .findBySessionId(connectedPlayer.player().sessionId()) - .orElseThrow(); - String buffered = - gameSession() - .bean(net.firedevops.firemud.cache.ScreenBufferService.class) - .get(context.tenantId(), context.gameInstanceId(), context.characterId()) - .map( - net.firedevops.firemud.cache.ScreenBufferService.BufferedScreen - ::protocolText) - .orElse(""); - assertThat(buffered).doesNotContain("Multiplayer burst "); - }); + connectedPlayer -> + assertThat(connectedPlayer.driver().responses()) + .noneMatch(payload -> payload.startsWith("ERROR "))); + SocialGroupsStubServer socialStub = STACK.socialStub(); - assertThat(socialStub.messageRequests()).isEmpty(); + assertThat(socialStub.messageRequests()).hasSize(CLIENT_COUNT); + assertThat(socialStub.messageRequests()) + .allSatisfy( + request -> { + assertThat(request.getTenantId()).isEqualTo(Long.toString(TENANT_ID)); + assertThat(request.getType()) + .isEqualTo(net.firedevops.firemud.socialgroups.v1.ChatType.CHAT_TYPE_SAY); + }); + assertThat( + socialStub.messageRequests().stream() + .map(request -> request.getContent()) + .collect(java.util.stream.Collectors.toSet())) + .isEqualTo( + connectedPlayers.stream() + .map(connectedPlayer -> sayText(connectedPlayer.player())) + .collect(java.util.stream.Collectors.toSet())); GameplayAsyncAssertions.assertMetricEventually( gameSession().bean(io.micrometer.core.instrument.MeterRegistry.class), COMMAND_WAIT, "gamesession.command.say.invocations", CLIENT_COUNT); - GameplayAsyncAssertions.assertMetricEventually( - gameSession().bean(io.micrometer.core.instrument.MeterRegistry.class), - COMMAND_WAIT, - "gamesession.command.say.failures", - CLIENT_COUNT, - "error", - "INVALID_ARGUMENT"); } finally { for (PlayerSessionDriver connectedPlayer : connectedPlayers) { connectedPlayer.driver().close(); @@ -316,24 +297,14 @@ private void runConcurrentDestinationLook(List connectedPla } private void runConcurrentSayBurst(List connectedPlayers) throws Exception { - List cursors = - connectedPlayers.stream().map(player -> player.driver().responseCount()).toList(); runConcurrently( connectedPlayers, connectedPlayer -> { connectedPlayer.driver().send("SAY " + sayText(connectedPlayer.player())); return null; }); - for (int i = 0; i < connectedPlayers.size(); i++) { - assertThat( - connectedPlayers - .get(i) - .driver() - .awaitTranscriptContainingAllAfter( - cursors.get(i), - "ERROR COMMUNICATION_NOT_DELIVERED", - "Sender Account identity unavailable")) - .contains("ERROR COMMUNICATION_NOT_DELIVERED"); + for (PlayerSessionDriver connectedPlayer : connectedPlayers) { + connectedPlayer.driver().awaitContains(expectedSayTranscript(connectedPlayer.player())); } } 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 d3315668c5..be39976aa0 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 @@ -74,6 +74,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); @@ -350,7 +351,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 7de2ef63a4..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 @@ -60,8 +60,7 @@ DurableResumeTranscriptExpiryJob.class }) class GameSessionLoginIntegrationTest { - private static final String DEMO_ACCOUNT_ID = "7"; - + private static final String ACCOUNT_UUID = "00000000-0000-4000-8000-000000000007"; @LocalServerPort private int port; @MockitoBean private AccountClient accountClient; @@ -113,7 +112,7 @@ void setUp() { .thenReturn( AuthenticateResponse.newBuilder() .setAuthToken("stub-token") - .setAccountId(DEMO_ACCOUNT_ID) + .setAccountId(ACCOUNT_UUID) .build()); when(sharedSettingsAuthorityReader.readOverrides(anyLong(), org.mockito.ArgumentMatchers.any())) .thenReturn(ScopedSettingsSnapshot.empty()); @@ -155,8 +154,12 @@ void loginCallsAccountServiceAndReturnsOk() throws Exception { } assertThat(payloads).anyMatch(s -> s.startsWith("OK LOGIN")); - assertThat(sessionContextService.findByTenantAndSessionId(42L, 1L)).isPresent(); - assertThat(redisValueStore).doesNotContainKey("accountrecentpresence:42:" + DEMO_ACCOUNT_ID); + assertThat(sessionContextService.findByTenantAndSessionId(42L, 1L)) + .hasValueSatisfying(context -> assertThat(context.accountId()).isEqualTo(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")); } 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 1f515c4830..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 @@ -41,6 +41,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.gamesession.service.GameplayPresence; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.SessionContextService; import net.firedevops.firemud.gamesession.testsupport.GameplayAsyncAssertions; @@ -118,9 +119,9 @@ @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 String DEMO_ACCOUNT_ID = "123"; private static final long CUTOVER_GAME_INSTANCE_ID = 3L; @Container @@ -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,16 +263,16 @@ void setUp() { .thenReturn( AuthenticateResponse.newBuilder() .setAuthToken("stub-token") - .setAccountId(DEMO_ACCOUNT_ID) + .setAccountId(ACCOUNT_UUID) .build()); org.mockito.Mockito.doReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId(DEMO_ACCOUNT_ID) + .setAccountId(ACCOUNT_UUID) .setTenantId("22") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(java.time.Instant.now().toString()) .build()) .when(accountClient) .getTenantMembershipForRuntime( @@ -284,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( @@ -296,7 +297,7 @@ void setUp() { net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("123") .setTenantId("22") - .setAccountId(DEMO_ACCOUNT_ID) + .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(DEMO_ACCOUNT_ID) + .setAccountId(ACCOUNT_UUID) .setName("Sora") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setLevel(7) @@ -314,7 +315,7 @@ void setUp() { .when(entityManagementClient) .listCharactersByAccount( eq("22"), - eq(DEMO_ACCOUNT_ID), + eq(ACCOUNT_UUID), eq("1"), eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(commandService.enqueue( @@ -464,13 +465,6 @@ void setUp() { }); } - private void assertNoAccountPresenceWritten() { - assertThat(firstPartyConnectStore.keySet()) - .noneMatch( - key -> key.startsWith("gameplaypresence:") || key.startsWith("accountrecentpresence:")); - assertThat(redisSetStore.keySet()).noneMatch(key -> key.startsWith("gameplaypresence:")); - } - @Test void websocketLoginThenLookUsesAuthenticatedPath() throws Exception { List payloads; @@ -663,23 +657,21 @@ void unexpectedDisconnectKeepsReplayEligibleForFreshReconnect() throws Exception System.currentTimeMillis()))); GameplayWebSocketDriver firstClient = openAdmittedGameplayDriver("41"); - assertThat(firstClient.responses()).anyMatch(payload -> payload.startsWith("OK PLAY")); - assertThat(gameplayPresenceService.findConnectedBySessionId(41L)).isEmpty(); - assertNoAccountPresenceWritten(); firstClient.abort(); GameplayAsyncAssertions.assertPresenceCountEventually( gameplayPresenceService, 22L, 1L, 0, java.time.Duration.ofSeconds(5)); assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)).isPresent(); - assertNoAccountPresenceWritten(); + assertThat(accountRecentPresenceService.findByAccountIds(22L, List.of(ACCOUNT_UUID))) + .containsKey(ACCOUNT_UUID); List secondPayloads; try (GameplayWebSocketDriver client = openAdmittedGameplayDriver("42")) { client.awaitContains("RECONNECT REPLAY APPEARS"); secondPayloads = client.responses(); GameplayAsyncAssertions.assertPresenceCountEventually( - gameplayPresenceService, 22L, 1L, 0, java.time.Duration.ofSeconds(5)); - assertThat(gameplayPresenceService.findConnectedBySessionId(42L)).isEmpty(); - assertNoAccountPresenceWritten(); + gameplayPresenceService, 22L, 1L, 1, java.time.Duration.ofSeconds(5)); + assertThat(gameplayPresenceService.listConnectedByGameInstance(22L, 1L)) + .anySatisfy(presence -> assertThat(presence.sessionId()).isEqualTo(42L)); } assertThat(secondPayloads).anyMatch(payload -> payload.contains("RECONNECT REPLAY APPEARS")); assertThat(secondPayloads).anyMatch(payload -> payload.startsWith("OK PLAY")); @@ -688,12 +680,9 @@ void unexpectedDisconnectKeepsReplayEligibleForFreshReconnect() throws Exception } @Test - void websocketAfkCommandIsAcceptedWithoutNumericOwnerPresence() throws Exception { + void websocketAfkCommandUpdatesLiveGameplayPresence() throws Exception { List payloads; try (GameplayWebSocketDriver client = openAdmittedGameplayDriver("41")) { - assertThat(client.responses()).anyMatch(payload -> payload.startsWith("OK PLAY")); - assertThat(gameplayPresenceService.findConnectedBySessionId(41L)).isEmpty(); - assertNoAccountPresenceWritten(); client.send("AFK"); GameplayAsyncAssertions.assertEventually( "AFK command enqueue", @@ -708,8 +697,21 @@ void websocketAfkCommandIsAcceptedWithoutNumericOwnerPresence() throws Exception && "AFK".equals(invocation.getArguments()[1]) && Boolean.FALSE.equals(invocation.getArguments()[2])); }); - assertThat(gameplayPresenceService.findConnectedBySessionId(41L)).isEmpty(); - assertNoAccountPresenceWritten(); + GameplayAsyncAssertions.assertEventually( + "AFK presence state", + java.time.Duration.ofSeconds(5), + () -> + gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() + .anyMatch(entry -> entry.sessionId() == 41L)); + GameplayAsyncAssertions.assertEventually( + "AFK explicit timestamp", + java.time.Duration.ofSeconds(5), + () -> + gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() + .filter(entry -> entry.sessionId() == 41L) + .findFirst() + .map(GameplayPresence::explicitAfkSinceEpochMs) + .isPresent()); payloads = client.responses(); } assertThat(payloads).anyMatch(payload -> payload.startsWith("OK PLAY")); @@ -828,7 +830,7 @@ void websocketLoginCanBrowseRealmsAndCharactersBeforePlay() throws Exception { verify(commandService, never()).enqueue("41", "CHARS demo", false); verify(entityManagementClient) .listCharactersByAccount( - "22", DEMO_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + "22", ACCOUNT_UUID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @Test @@ -903,7 +905,7 @@ void websocketActiveGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("789") .setTenantId("22") - .setAccountId(DEMO_ACCOUNT_ID) + .setAccountId(ACCOUNT_UUID) .setName("CutoverArrival") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setLevel(1) @@ -913,7 +915,7 @@ void websocketActiveGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() .when(entityManagementClient) .listCharactersByAccount( "22", - DEMO_ACCOUNT_ID, + ACCOUNT_UUID, Long.toString(CUTOVER_GAME_INSTANCE_ID), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); @@ -946,7 +948,7 @@ void websocketActiveGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() org.mockito.Mockito.verify(entityManagementClient) .listCharactersByAccount( "22", - DEMO_ACCOUNT_ID, + ACCOUNT_UUID, Long.toString(CUTOVER_GAME_INSTANCE_ID), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @@ -1005,7 +1007,7 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)) .hasValueSatisfying( context -> { - assertThat(context.accountId()).isEqualTo(DEMO_ACCOUNT_ID); + assertThat(context.accountId()).isEqualTo(ACCOUNT_UUID); assertThat(context.gameInstanceId()).isZero(); assertThat(context.characterId()).isZero(); assertThat(context.bootstrapGameInstanceId()).isEqualTo(2L); @@ -1014,7 +1016,6 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots assertThat(context.pointerVersion()).isEqualTo(1L); }); assertThat(gameplayPresenceService.findConnectedBySessionId(41L)).isEmpty(); - assertNoAccountPresenceWritten(); } private GameplayWebSocketDriver openGameplayDriver(String sessionId) { @@ -1194,11 +1195,9 @@ void firstPartyUnavailableBootstrapDeniesWithoutLoginLobbyGameplayOrReplayEffect void unqualifiedFirstPartyReconnectDoesNotReplaceRetainedOrdinaryGameplayContext() throws Exception { try (GameplayWebSocketDriver ordinary = openAdmittedGameplayDriver("2")) { - assertThat(ordinary.responses()).anyMatch(payload -> payload.startsWith("OK PLAY")); var retained = sessionContextService.findByTenantAndSessionId(22L, 2L).orElseThrow(); var retainedPresence = gameplayPresenceService.findConnectedBySessionId(2L); - assertThat(retainedPresence).isEmpty(); - assertNoAccountPresenceWritten(); + assertThat(retainedPresence).isPresent(); try (GameplayWebSocketDriver reconnecting = openUnqualifiedFirstPartyDriver("2", "unqualified-context")) { var close = reconnecting.awaitClosed(); @@ -1209,7 +1208,6 @@ void unqualifiedFirstPartyReconnectDoesNotReplaceRetainedOrdinaryGameplayContext assertThat(firstPartyConnectStore) .doesNotContainKey("sessionctx:first-party:2:connect-context"); assertThat(gameplayPresenceService.findConnectedBySessionId(2L)).isEqualTo(retainedPresence); - assertNoAccountPresenceWritten(); int responseBaseline = ordinary.responses().size(); ordinary.send("LOOK"); ordinary.awaitTranscriptContainingAllAfter(responseBaseline, "Room: Login Hall (ID: R-1021)"); 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/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..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 @@ -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; @@ -39,11 +41,13 @@ 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; 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 +104,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,12 +113,12 @@ void setUp() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .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( @@ -123,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(), @@ -131,7 +135,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 +174,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 +189,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -196,7 +207,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -214,7 +225,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -233,7 +244,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -251,13 +262,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 +285,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 +316,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 +368,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 +381,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 +405,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 +423,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 +437,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 +446,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 +465,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 9007L, "Emberline", @@ -467,7 +483,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 9007L, "Emberline", @@ -487,7 +503,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 9007L, "Emberline", @@ -507,15 +523,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 +547,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 +574,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 +610,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 +629,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 +648,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 +678,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 +707,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 +723,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 +752,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 +767,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 +793,7 @@ void playResumeDoesNotPublishSpawnEvent() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "Emberline", @@ -777,10 +808,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 +835,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 +853,7 @@ void playIgnoresStaleExistingBindingAfterNormalization() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -839,12 +875,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 +907,7 @@ void playIgnoresExistingBindingWithoutRoomRegion() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -902,7 +938,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 +950,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 +999,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 +1055,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 +1067,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 +1095,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 +1125,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 +1151,7 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "first-party:123", 0L, null, @@ -1150,18 +1187,18 @@ 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) .setMembershipVersion(2L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1188,7 +1225,7 @@ void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { new SessionContext( 1L, 23L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -1206,12 +1243,12 @@ void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(false) .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1232,17 +1269,17 @@ 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) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1276,14 +1313,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"), @@ -1300,7 +1337,7 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(false).build()); + .thenReturn(realmGrantResponse(false)); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1308,7 +1345,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"), @@ -1326,7 +1363,7 @@ void playInvisibleRealmWithDeniedGrantClearsBinding() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(GetRealmAccessGrantForRuntimeResponse.newBuilder().setGranted(false).build()); + .thenReturn(realmGrantResponse(false)); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); @@ -1391,12 +1428,50 @@ 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(); + } + @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,18 +1498,18 @@ 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) .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")); @@ -1453,18 +1528,18 @@ 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) .setMembershipVersion(4L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1478,17 +1553,118 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "join_required"); } + @ParameterizedTest + @ValueSource( + strings = { + "c04bf730-5f95-4357-a850-ac29eca1754e", + "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(Instant.now().toString()) + .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 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 = 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 +1726,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( @@ -1559,7 +1735,7 @@ void playBlockedByEntitlementsReturnsBillingBlocked() { .setGameplayAvailable(false) .setEntitlementVersion(5L) .setTenantBillingSequence(5L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1580,7 +1756,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 +1788,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 +1820,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 +1850,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 +1866,7 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -1715,7 +1892,7 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -1734,7 +1911,7 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 7001L, "demo", @@ -1767,7 +1944,7 @@ private SessionContext previewRealmContext() { return new SessionContext( 1L, 22L, - "123", + ACCOUNT_ID, "demo@example.com", 123L, "Emberline", @@ -1789,6 +1966,23 @@ 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 GameplayCatalogProperties.World world( String slug, String displayName, List realms) { GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); @@ -1904,7 +2098,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..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 @@ -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,17 +165,17 @@ void setUp() { .thenReturn(CommandEnqueueResult.success()); when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken("jwt").setAccountId("77").build()); + AuthenticateResponse.newBuilder().setAuthToken("jwt").setAccountId(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) .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(java.time.Instant.now().toString()) .build()); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -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) @@ -195,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(), @@ -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,12 +467,12 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("77") + .setAccountId(ACCOUNT_ID) .setTenantId("22") .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 ddbf4bc986..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 @@ -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,18 +166,18 @@ 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) .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(java.time.Instant.now().toString()) .build()); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -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) @@ -197,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( @@ -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/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/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/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/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/GameplayCommandTestFixturesTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/GameplayCommandTestFixturesTest.java index 752e85020c..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 @@ -13,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"); @@ -25,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); @@ -42,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()); @@ -99,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"); 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 79bca5cb99..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 @@ -17,12 +17,8 @@ class EntityManagementStubServerTest { @Test - void explicitUuidRosterRetainsExactTenantAndAccountOwnership() throws Exception { + void listsOnlyThePersistedSharedCharacterForTheRequestedTenantAndAccount() throws Exception { try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { - server.setCharacters( - List.of("Emberline", "Sora", "Nyx").stream() - .map(ChatTestFixtures::characterByName) - .toList()); ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); try { @@ -48,55 +44,28 @@ void explicitUuidRosterRetainsExactTenantAndAccountOwnership() throws Exception } @Test - void parentPhaseDefaultsAndResetRetainDeclaredNumericFakeOwners() throws Exception { + void resetCharactersRestoresDefaultSharedCharactersAfterAnEmptyOverride() throws Exception { try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { + server.setCharacters(List.of()); ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); try { - var stub = EntityManagementServiceGrpc.newBlockingStub(channel); - for (boolean reset : List.of(false, true)) { - if (reset) { - server.setCharacters(List.of()); - assertThat( - listCharacters(stub, "1", "7", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .getCharactersList()) - .isEmpty(); - server.resetCharacters(); - } - for (FixtureCharacter fixture : - List.of( - new FixtureCharacter("7", "Emberline"), - new FixtureCharacter("8", "Sora"), - new FixtureCharacter("9", "Nyx"))) { - assertThat( - listCharacters( - stub, - "1", - fixture.accountId(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .getCharactersList()) - .containsExactly( - sharedCharacter(fixture.name()).toBuilder() - .setAccountId(fixture.accountId()) - .build()); - assertThat( - listCharacters( - stub, - "2", - fixture.accountId(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .getCharactersList()) - .isEmpty(); - } - assertThat( - listCharacters( - stub, - "1", - accountUuid(7L), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .getCharactersList()) - .isEmpty(); - } + 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(); } @@ -161,10 +130,6 @@ void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { @Test void unknownOrMismatchedTenantAndAccountReturnNoCharacters() throws Exception { try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { - server.setCharacters( - List.of("Emberline", "Sora", "Nyx").stream() - .map(ChatTestFixtures::characterByName) - .toList()); ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); try { @@ -193,10 +158,6 @@ void unknownOrMismatchedTenantAndAccountReturnNoCharacters() throws Exception { @Test void unsupportedPlayableStateScopesReturnNoCharacters() throws Exception { try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { - server.setCharacters( - List.of("Emberline", "Sora", "Nyx").stream() - .map(ChatTestFixtures::characterByName) - .toList()); ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); try { 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/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/stubs/EntityManagementStubServer.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java index ee1d48da6f..8c4f50a040 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java @@ -264,20 +264,7 @@ public void resetActorState() { private static List defaultCharacters() { return List.of("Emberline", "Sora", "Nyx").stream() - .map( - name -> { - long owner = - switch (name) { - case "Emberline" -> ChatTestFixtures.EMBERLINE_ACCOUNT_ROW_ID; - case "Sora" -> ChatTestFixtures.SORA_ACCOUNT_ROW_ID; - case "Nyx" -> ChatTestFixtures.NYX_ACCOUNT_ROW_ID; - default -> throw new AssertionError(name); - }; - // Parent-phase Account authentication still uses its declared numeric fake owner. - return ChatTestFixtures.characterByName(name).toBuilder() - .setAccountId(Long.toString(owner)) - .build(); - }) + .map(ChatTestFixtures::characterByName) .toList(); } 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..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 @@ -4,10 +4,8 @@ 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; import net.firedevops.firemud.loggingadmin.repository.PlayerReportRepository; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; @@ -32,14 +30,14 @@ public class TestDataSeeder implements ApplicationRunner { private final LogEventRepository logEventRepository; private final PlayerReportRepository playerReportRepository; - private final ModerationActionRepository moderationActionRepository; @Override @Transactional 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 +70,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/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/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/resources/db/migration/V1003__moderation_account_uuid.sql b/services/logging-admin-service/src/main/resources/db/migration/V1003__moderation_account_uuid.sql new file mode 100644 index 0000000000..9ae5a516bd --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V1003__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..2bcd713099 --- /dev/null +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java @@ -0,0 +1,126 @@ +package net.firedevops.firemud.loggingadmin; + +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; +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("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() { + 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')", + 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("1003").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 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'", + String.class)) + .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) + .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 3c431d0dde..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; @@ -37,7 +38,7 @@ @WithFiremudPrivilegedHttpAuthTestProperties class ModerationActionControllerTest { - private static final String CALLER_ACCOUNT_UUID = "f22f310d-5464-45f0-9dc4-c37353004403"; + private static final String ACCOUNT_ID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; @Autowired private MockMvc mockMvc; private final ObjectMapper objectMapper = new ObjectMapper(); @@ -52,11 +53,11 @@ 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( - CALLER_ACCOUNT_UUID, - Map.of("accountId", CALLER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -77,15 +78,12 @@ 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( - CALLER_ACCOUNT_UUID, - Map.of( - "accountId", - CALLER_ACCOUNT_UUID, - "scopedRoles", - Map.of("8", List.of("moderator")))); + ACCOUNT_ID, + Map.of("accountId", ACCOUNT_ID, "scopedRoles", Map.of("8", List.of("moderator")))); mockMvc .perform( @@ -98,11 +96,11 @@ 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( - CALLER_ACCOUNT_UUID, - Map.of("accountId", CALLER_ACCOUNT_UUID, "globalRoles", List.of("platformAdmin"))); + ACCOUNT_ID, Map.of("accountId", ACCOUNT_ID, "globalRoles", List.of("platformAdmin"))); mockMvc .perform( @@ -116,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); + } } 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..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 @@ -36,15 +33,11 @@ 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()); } @Test @@ -54,17 +47,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()); 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/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..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; @@ -32,19 +33,32 @@ 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); 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 @@ -54,12 +68,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/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 1efcc33a47..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 @@ -17,11 +17,13 @@ import net.firedevops.firemud.gamesession.test.LookTestFixtures; import net.firedevops.firemud.gamesession.test.stubs.EntityManagementStubServer; import net.firedevops.firemud.gamesession.test.stubs.SocialGroupsStubServer; +import net.firedevops.firemud.gamesession.testsupport.GameplayAsyncAssertions; import net.firedevops.firemud.gamesession.testsupport.GameplayCrossServiceStack; import net.firedevops.firemud.gamesession.testsupport.GameplayEntityAssertions; import net.firedevops.firemud.gamesession.testsupport.GameplayTranscriptMatchers; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketDriver; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketScenarios; +import net.firedevops.firemud.socialgroups.v1.ChatType; import net.firedevops.firemud.tcpproxy.stub.GatewayStubApplication; import net.firedevops.firemud.tcpproxy.telnet.TelnetServer; import net.firedevops.firemud.tcpproxy.testsupport.GameplayTelnetDriver; @@ -125,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 @@ -263,54 +270,124 @@ void telnetAndGatewayWebSocketCanMoveNorthOnSharedRuntime() throws Exception { } @Test - void telnetNumericItemMutationsAreRefusedWhileEquipmentRemainsAvailable() throws Exception { + void telnetItemAndEquipmentLoopMatchesWebSocketCommandSurface() throws Exception { ensureTestServicesStarted(); + + String roomInventoryBeforePickup; + String pickupResponse; + String containerViewResponse; + String putResponse; + String takeResponse; + String dropResponse; + String roomInventoryAfterDrop; + String emptyEquipmentResponse; + String wearResponse; + String equipmentResponse; + String removeResponse; + String incompatibleResponse; try (GameplayTelnetDriver client = openReadyTelnetClient()) { - client.sendLine("INV HERE"); - String groundBefore = client.readBlockContaining("Room Inventory:"); - client.sendLine("INV"); - String carriedBefore = client.readBlockContaining("Inventory:"); - assertThat(groundBefore).contains("Torch", "Backpack"); - assertThat(carriedBefore).contains("Leather Cap", "Iron Boots").doesNotContain("Torch"); - client.sendLine("GET Torch"); - assertThat(client.readLineContaining("ERROR INVENTORY_UNAVAILABLE")) - .contains("ERROR INVENTORY_UNAVAILABLE"); - client.sendLine("DROP Leather Cap"); - assertThat(client.readLineContaining("ERROR INVENTORY_UNAVAILABLE")) - .contains("ERROR INVENTORY_UNAVAILABLE"); client.sendLine("INV HERE"); - assertThat(client.readBlockContaining("Room Inventory:")) - .contains( + roomInventoryBeforePickup = client.readBlockContaining("Room Inventory:"); + client.sendLine("GET Torch"); + pickupResponse = + client.readTranscriptContainingAll( + "You pick up Torch.", + "Inventory:", "- Torch [torch#1] (A small torch)", + "Room Inventory:", "- Backpack [backpack#1] (A weathered backpack)"); - client.sendLine("INV"); - assertThat(client.readBlockContaining("Inventory:")) - .contains( - "- Leather Cap [cap#1] (A small cap)", "- Iron Boots [boots#1] (Heavy iron boots)") - .doesNotContain("Torch"); - assertNoItemMutationRequests(); client.sendLine("CONTAINER Backpack"); - assertThat(client.readBlockContaining("Container: Backpack [backpack#1]")) - .contains("- Ration [ration#1] (A dry trail ration)") - .doesNotContain("Torch"); + containerViewResponse = client.readBlockContaining("Container: Backpack [backpack#1]"); + client.sendLine("PUT Torch INTO Backpack"); + putResponse = client.readBlockContaining("You put Torch into Backpack."); + client.sendLine("TAKE Torch FROM Backpack"); + takeResponse = client.readBlockContaining("You take Torch from Backpack."); + client.sendLine("DROP Torch"); + dropResponse = + client.readTranscriptContainingAll( + "You drop Torch.", + "Inventory:", + "- Leather Cap [cap#1] (A small cap)", + "- Iron Boots [boots#1] (Heavy iron boots)", + "Room Inventory:", + "- Torch [torch#1] (A small torch)"); + client.sendLine("INV HERE"); + roomInventoryAfterDrop = client.readBlockContaining("Room Inventory:"); client.sendLine("EQUIPMENT"); - assertThat(client.readBlockContaining("You have nothing equipped.")) - .contains("You have nothing equipped."); + emptyEquipmentResponse = client.readBlockContaining("You have nothing equipped."); client.sendLine("WEAR Leather Cap"); - assertThat(client.readLineContaining("You wear Leather Cap.")) - .contains("You wear Leather Cap."); + wearResponse = client.readLineContaining("You wear Leather Cap."); client.sendLine("EQUIPMENT"); - assertThat(client.readBlockContaining("Equipment:")) - .contains("- HEAD: Leather Cap [cap#1] (A small cap)"); + equipmentResponse = client.readBlockContaining("Equipment:"); client.sendLine("REMOVE HEAD"); - assertThat(client.readLineContaining("You remove Leather Cap.")) - .contains("You remove Leather Cap."); + removeResponse = client.readLineContaining("You remove Leather Cap."); client.sendLine("WEAR Iron Boots"); - assertThat(client.readLineContaining("ERROR SLOT_INCOMPATIBLE")) - .contains("ERROR SLOT_INCOMPATIBLE", "Iron Boots cannot be worn by this body layout."); + incompatibleResponse = client.readLineContaining("ERROR SLOT_INCOMPATIBLE"); } + + assertThat(roomInventoryBeforePickup) + .contains("- Torch [torch#1] (A small torch)") + .contains("- Backpack [backpack#1] (A weathered backpack)"); + assertThat(pickupResponse) + .contains("You pick up Torch.") + .contains("Inventory:") + .contains("- Torch [torch#1] (A small torch)") + .contains("Room Inventory:") + .contains("- Backpack [backpack#1] (A weathered backpack)"); + assertThat(containerViewResponse) + .contains("Container: Backpack [backpack#1]") + .contains("- Ration [ration#1] (A dry trail ration)"); + assertThat(putResponse) + .contains("You put Torch into Backpack.") + .contains("- Torch [torch#1] (A small torch)"); + assertThat(takeResponse) + .contains("You take Torch from Backpack.") + .contains("- Ration [ration#1] (A dry trail ration)"); + assertThat(dropResponse) + .contains("You drop Torch.") + .contains("Inventory:") + .contains("- Leather Cap [cap#1] (A small cap)") + .contains("- Iron Boots [boots#1] (Heavy iron boots)") + .contains("Room Inventory:") + .contains("- Torch [torch#1] (A small torch)"); + assertThat(roomInventoryAfterDrop).contains("- Torch [torch#1] (A small torch)"); + assertThat(emptyEquipmentResponse).contains("You have nothing equipped."); + assertThat(wearResponse).contains("You wear Leather Cap."); + assertThat(equipmentResponse).contains("- HEAD: Leather Cap [cap#1] (A small cap)"); + assertThat(removeResponse).contains("You remove Leather Cap."); + assertThat(incompatibleResponse) + .contains("ERROR SLOT_INCOMPATIBLE") + .contains("Iron Boots cannot be worn by this body layout."); + GameplayEntityAssertions.assertPickup( + entityStub().lastPickupRequest(), + String.valueOf(TENANT_ID), + ChatTestFixtures.PLAYER_EMBERLINE, + null, + LookTestFixtures.ROOM_ID, + "torch"); + GameplayEntityAssertions.assertDrop( + entityStub().lastDropRequest(), + String.valueOf(TENANT_ID), + ChatTestFixtures.PLAYER_EMBERLINE, + null, + LookTestFixtures.ROOM_ID, + "torch"); + GameplayEntityAssertions.assertPut( + entityStub().lastPutRequest(), + String.valueOf(TENANT_ID), + ChatTestFixtures.PLAYER_EMBERLINE, + "container-backpack-1", + "torch", + "torch-ground-1"); + GameplayEntityAssertions.assertTake( + entityStub().lastTakeRequest(), + String.valueOf(TENANT_ID), + ChatTestFixtures.PLAYER_EMBERLINE, + "container-backpack-1", + "torch", + ""); GameplayEntityAssertions.assertRemove( entityStub().lastRemoveRequest(), String.valueOf(TENANT_ID), @@ -325,60 +402,80 @@ void telnetNumericItemMutationsAreRefusedWhileEquipmentRemainsAvailable() throws } @Test - void numericItemRefusalsPreserveSharedInventoryAcrossWebSocketLogout() throws Exception { + void telnetItemLoopStillSucceedsAfterWebSocketLogoutOnSharedRuntime() throws Exception { ensureTestServicesStarted(); - try (GameplayWebSocketDriver client = openReadyGatewayWebSocketClient("gateway-1")) { - int before = client.responseCount(); - client.send("INV HERE"); + + try (GameplayWebSocketDriver webSocketClient = openReadyGatewayWebSocketClient("gateway-1")) { + webSocketClient.send("INV HERE"); + assertThat( + webSocketClient.awaitResponseMatching( + response -> + response.contains("Room Inventory:") + && response.contains("Torch") + && response.contains("Backpack"), + "room inventory before pickup")) + .contains("Room Inventory:"); + webSocketClient.send("GET Torch"); + assertThat( + webSocketClient.awaitResponseMatching( + response -> response.contains("You pick up Torch."), "pickup response")) + .contains("You pick up Torch."); + webSocketClient.send("CONTAINER Backpack"); + assertThat( + webSocketClient.awaitResponseMatching( + response -> + response.contains("Container: Backpack [backpack#1]") + && response.contains("Ration"), + "container view")) + .contains("Container: Backpack [backpack#1]"); + webSocketClient.send("PUT Torch INTO Backpack"); + assertThat( + webSocketClient.awaitResponseMatching( + response -> response.contains("You put Torch into Backpack."), "put response")) + .contains("You put Torch into Backpack."); assertThat( - client.awaitTranscriptContainingAllAfter( - before, "Room Inventory:", "Torch", "Backpack")) - .contains("Torch", "Backpack"); - before = client.responseCount(); - client.send("GET Torch"); - assertThat(client.awaitTranscriptContainingAllAfter(before, "ERROR INVENTORY_UNAVAILABLE")) - .contains("ERROR INVENTORY_UNAVAILABLE"); - before = client.responseCount(); - client.send("DROP Leather Cap"); - assertThat(client.awaitTranscriptContainingAllAfter(before, "ERROR INVENTORY_UNAVAILABLE")) - .contains("ERROR INVENTORY_UNAVAILABLE"); - before = client.responseCount(); - client.send("INV HERE"); + webSocketClient.awaitResponseMatching( + response -> + response.contains("Container: Backpack [backpack#1]") + && response.contains("Torch"), + "container view after put")) + .contains("Container: Backpack [backpack#1]"); + webSocketClient.send("TAKE Torch FROM Backpack"); assertThat( - client.awaitTranscriptContainingAllAfter( - before, "Room Inventory:", "Torch", "Backpack")) - .contains("Torch", "Backpack"); - before = client.responseCount(); - client.send("INV"); + webSocketClient.awaitResponseMatching( + response -> response.contains("You take Torch from Backpack."), "take response")) + .contains("You take Torch from Backpack."); assertThat( - client.awaitTranscriptContainingAllAfter( - before, "Inventory:", "Leather Cap", "Iron Boots")) - .doesNotContain("Torch"); - assertNoItemMutationRequests(); - before = client.responseCount(); - client.send("LOGOUT"); - assertThat(client.awaitTranscriptContainingAllAfter(before, "OK LOGOUT", "Logged out.")) + webSocketClient.awaitResponseMatching( + response -> + response.contains("Container: Backpack [backpack#1]") + && response.contains("Ration"), + "container view after take")) + .contains("Container: Backpack [backpack#1]"); + webSocketClient.send("DROP Torch"); + assertThat( + webSocketClient.awaitResponseMatching( + response -> response.contains("You drop Torch."), "drop response")) + .contains("You drop Torch."); + webSocketClient.send("LOGOUT"); + assertThat( + webSocketClient.awaitResponseMatching( + response -> response.contains("OK LOGOUT") && response.contains("Logged out."), + "logout response")) .contains("OK LOGOUT"); } - try (GameplayTelnetDriver client = openReadyTelnetClient()) { - client.sendLine("GET Torch"); - assertThat(client.readLineContaining("ERROR INVENTORY_UNAVAILABLE")) - .contains("ERROR INVENTORY_UNAVAILABLE"); - client.sendLine("DROP Leather Cap"); - assertThat(client.readLineContaining("ERROR INVENTORY_UNAVAILABLE")) - .contains("ERROR INVENTORY_UNAVAILABLE"); - client.sendLine("INV HERE"); - assertThat(client.readBlockContaining("Room Inventory:")).contains("Torch", "Backpack"); - client.sendLine("INV"); - assertThat(client.readBlockContaining("Inventory:")) - .contains("Leather Cap", "Iron Boots") - .doesNotContain("Torch"); - client.sendLine("CONTAINER Backpack"); - assertThat(client.readBlockContaining("Container: Backpack [backpack#1]")) - .contains("Ration") - .doesNotContain("Torch"); + + try (GameplayTelnetDriver telnetClient = openReadyTelnetClient()) { + telnetClient.sendLine("GET Torch"); + assertThat(telnetClient.readBlockContaining("You pick up Torch.")) + .contains("You pick up Torch."); + telnetClient.sendLine("PUT Torch INTO Backpack"); + assertThat(telnetClient.readBlockContaining("You put Torch into Backpack.")) + .contains("You put Torch into Backpack."); + telnetClient.sendLine("TAKE Torch FROM Backpack"); + assertThat(telnetClient.readBlockContaining("You take Torch from Backpack.")) + .contains("You take Torch from Backpack."); } - assertNoItemMutationRequests(); } @Test @@ -475,185 +572,151 @@ void telnetSecondConnectionTakesOverGameplayBinding() throws Exception { } @Test - void telnetNumericWhisperAndTellAreRefusedWithoutSocialOrTargetWrites() throws Exception { + void telnetCommunicationMatchesCanonicalTranscripts() throws Exception { ensureTestServicesStarted(); entityStub().setRoomEntities(ChatTestFixtures.sampleEntities()); seedLiveTargetSession(); - SessionContext target = - gameSession() - .bean(SessionContextService.class) - .findByGameplayName(TENANT_ID, DEMO_WORLD_INSTANCE_ID, "Sora") - .orElseThrow(); - ScreenBufferService buffers = gameSession().bean(ScreenBufferService.class); - var targetBefore = - buffers.get(target.tenantId(), target.gameInstanceId(), target.characterId()); + + String telnetWhisperResponse; + String telnetTellResponse; try (GameplayTelnetDriver client = openReadyTelnetClient()) { - for (String command : List.of("WHISPER Sora Keep quiet", "TELL Sora Meet me at the forge")) { - client.sendLine(command); - assertThat(client.readLineContaining("ERROR COMMUNICATION_NOT_DELIVERED")) - .contains("ERROR COMMUNICATION_NOT_DELIVERED", "Sender Account identity unavailable"); - assertThat(socialStub().lastRequest()).isEmpty(); - assertThat(buffers.get(target.tenantId(), target.gameInstanceId(), target.characterId())) - .isEqualTo(targetBefore); - } + + client.sendLine("WHISPER Sora Keep quiet"); + telnetWhisperResponse = client.readLineContaining(ChatTestFixtures.canonicalWhisperText()); + GameplayEntityAssertions.assertMessage( + socialStub().lastRequest(), + ChatType.CHAT_TYPE_WHISPER, + ChatTestFixtures.PLAYER_SORA, + null, + false); + + client.sendLine("TELL Sora Meet me at the forge"); + telnetTellResponse = client.readLineContaining(ChatTestFixtures.canonicalTellText()); } + + assertThat(telnetWhisperResponse).contains(ChatTestFixtures.canonicalWhisperText()); + assertThat(telnetTellResponse).contains(ChatTestFixtures.canonicalTellText()); + GameplayEntityAssertions.assertMessage( + socialStub().lastRequest(), + ChatType.CHAT_TYPE_TELL, + ChatTestFixtures.PLAYER_SORA, + null, + false); } @Test - void telnetNumericWhisperDoesNotWriteTargetOrObserverViews() throws Exception { + void telnetWhisperDeliversTargetAndObserverViews() throws Exception { ensureTestServicesStarted(); entityStub().setRoomEntities(ChatTestFixtures.sampleEntities()); + try (GameplayTelnetScenarios.ThreePlayerScenario scenario = GameplayTelnetScenarios.openReadyTrio( this::openTelnetClient, characterAdmission(GameplayTelnetScenarios.DEMO_LOGIN_EMAIL, "Emberline"), characterAdmission("sora@example.com", "Sora"), characterAdmission("nyx@example.com", "Nyx"))) { - SessionContextService contexts = gameSession().bean(SessionContextService.class); - ActiveTransportSessionRegistry transports = + SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); + ActiveTransportSessionRegistry sessionRegistry = gameSession().bean(ActiveTransportSessionRegistry.class); - ScreenBufferService buffers = gameSession().bean(ScreenBufferService.class); - SessionContext target = - contexts.findByGameplayName(TENANT_ID, DEMO_WORLD_INSTANCE_ID, "Sora").orElseThrow(); - SessionContext observer = - contexts.findByGameplayName(TENANT_ID, DEMO_WORLD_INSTANCE_ID, "Nyx").orElseThrow(); - assertThat(transports.find(target.sessionId())).isPresent(); - assertThat(transports.find(observer.sessionId())).isPresent(); - var targetBefore = - buffers - .get(target.tenantId(), target.gameInstanceId(), target.characterId()) - .map( - screen -> - screen.entries().stream() - .filter(entry -> !"look_view".equals(entry.payloadType())) - .toList()) - .orElse(List.of()); - var observerBefore = - buffers - .get(observer.tenantId(), observer.gameInstanceId(), observer.characterId()) - .map( - screen -> - screen.entries().stream() - .filter(entry -> !"look_view".equals(entry.payloadType())) - .toList()) - .orElse(List.of()); + ScreenBufferService screenBufferService = gameSession().bean(ScreenBufferService.class); + SessionContext targetContext = + sessionContextService + .findByGameplayName(TENANT_ID, DEMO_WORLD_INSTANCE_ID, "Sora") + .orElseThrow(); + SessionContext observerContext = + sessionContextService + .findByGameplayName(TENANT_ID, DEMO_WORLD_INSTANCE_ID, "Nyx") + .orElseThrow(); + assertThat(sessionRegistry.find(targetContext.sessionId())).isPresent(); + assertThat(sessionRegistry.find(observerContext.sessionId())).isPresent(); + scenario.actor().sendLine("WHISPER Sora Keep quiet"); - assertThat(scenario.actor().readLineContaining("ERROR COMMUNICATION_NOT_DELIVERED")) - .contains("ERROR COMMUNICATION_NOT_DELIVERED", "Sender Account identity unavailable"); - assertThat(socialStub().lastRequest()).isEmpty(); - // The initial LOOK projection can arrive between these reads; compare communication history. + GameplayAsyncAssertions.assertBufferedScreenEventuallyContains( + screenBufferService, + targetContext, + COMMAND_WAIT, + ChatTestFixtures.canonicalWhisperTargetText()); + GameplayAsyncAssertions.assertBufferedScreenEventuallyContains( + screenBufferService, + observerContext, + COMMAND_WAIT, + ChatTestFixtures.canonicalWhisperObserverMetadataText()); + assertThat(scenario.actor().readLineContaining(ChatTestFixtures.canonicalWhisperText())) + .contains(ChatTestFixtures.canonicalWhisperText()); assertThat( - buffers - .get(target.tenantId(), target.gameInstanceId(), target.characterId()) - .map( - screen -> - screen.entries().stream() - .filter(entry -> !"look_view".equals(entry.payloadType())) - .toList()) - .orElse(List.of())) - .isEqualTo(targetBefore); - assertThat( - buffers - .get(observer.tenantId(), observer.gameInstanceId(), observer.characterId()) - .map( - screen -> - screen.entries().stream() - .filter(entry -> !"look_view".equals(entry.payloadType())) - .toList()) - .orElse(List.of())) - .isEqualTo(observerBefore); + scenario.target().readLineContaining(ChatTestFixtures.canonicalWhisperTargetText())) + .contains(ChatTestFixtures.canonicalWhisperTargetText()); + assertThat(scenario.observer().readLineContaining("Emberline whispers something to Sora.")) + .contains(ChatTestFixtures.canonicalWhisperObserverMetadataText()); } } @Test - void telnetNumericSayDoesNotWriteRoomListenerView() throws Exception { + void telnetSayDeliversRoomListenerView() throws Exception { ensureTestServicesStarted(); entityStub().setRoomEntities(ChatTestFixtures.sampleEntities()); + try (GameplayTelnetScenarios.TwoPlayerScenario scenario = GameplayTelnetScenarios.openReadyPair( this::openTelnetClient, characterAdmission(GameplayTelnetScenarios.DEMO_LOGIN_EMAIL, "Emberline"), characterAdmission("sora@example.com", "Sora"))) { - SessionContext target = - gameSession() - .bean(SessionContextService.class) + SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); + ActiveTransportSessionRegistry sessionRegistry = + gameSession().bean(ActiveTransportSessionRegistry.class); + ScreenBufferService screenBufferService = gameSession().bean(ScreenBufferService.class); + SessionContext targetContext = + sessionContextService .findByGameplayName(TENANT_ID, DEMO_WORLD_INSTANCE_ID, "Sora") .orElseThrow(); - assertThat(gameSession().bean(ActiveTransportSessionRegistry.class).find(target.sessionId())) - .isPresent(); - ScreenBufferService buffers = gameSession().bean(ScreenBufferService.class); - var targetBefore = - buffers - .get(target.tenantId(), target.gameInstanceId(), target.characterId()) - .map( - screen -> - screen.entries().stream() - .filter(entry -> !"look_view".equals(entry.payloadType())) - .toList()); + assertThat(sessionRegistry.find(targetContext.sessionId())).isPresent(); + scenario.actor().sendLine("SAY hello travelers"); - assertThat(scenario.actor().readLineContaining("ERROR COMMUNICATION_NOT_DELIVERED")) - .contains("ERROR COMMUNICATION_NOT_DELIVERED", "Sender Account identity unavailable"); - assertThat(socialStub().lastRequest()).isEmpty(); - assertThat( - buffers - .get(target.tenantId(), target.gameInstanceId(), target.characterId()) - .map( - screen -> - screen.entries().stream() - .filter(entry -> !"look_view".equals(entry.payloadType())) - .toList())) - .isEqualTo(targetBefore); + GameplayAsyncAssertions.assertBufferedScreenEventuallyContains( + screenBufferService, + targetContext, + COMMAND_WAIT, + ChatTestFixtures.canonicalSayListenerText()); + assertThat(scenario.actor().readLineContaining(ChatTestFixtures.canonicalSayText())) + .contains(ChatTestFixtures.canonicalSayText()); + assertThat(scenario.target().readLineContaining(ChatTestFixtures.canonicalSayListenerText())) + .contains(ChatTestFixtures.canonicalSayListenerText()); } } @Test - void telnetNumericTellDoesNotWriteTargetView() throws Exception { + void telnetTellDeliversTargetView() throws Exception { ensureTestServicesStarted(); entityStub().setRoomEntities(ChatTestFixtures.sampleEntities()); + try (GameplayTelnetScenarios.TwoPlayerScenario scenario = GameplayTelnetScenarios.openReadyPair( this::openTelnetClient, characterAdmission(GameplayTelnetScenarios.DEMO_LOGIN_EMAIL, "Emberline"), characterAdmission("sora@example.com", "Sora"))) { - SessionContext target = - gameSession() - .bean(SessionContextService.class) + SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); + ActiveTransportSessionRegistry sessionRegistry = + gameSession().bean(ActiveTransportSessionRegistry.class); + ScreenBufferService screenBufferService = gameSession().bean(ScreenBufferService.class); + SessionContext targetContext = + sessionContextService .findByGameplayName(TENANT_ID, DEMO_WORLD_INSTANCE_ID, "Sora") .orElseThrow(); - assertThat(gameSession().bean(ActiveTransportSessionRegistry.class).find(target.sessionId())) - .isPresent(); - ScreenBufferService buffers = gameSession().bean(ScreenBufferService.class); - var targetBefore = - buffers - .get(target.tenantId(), target.gameInstanceId(), target.characterId()) - .map( - screen -> - screen.entries().stream() - .filter(entry -> !"look_view".equals(entry.payloadType())) - .toList()); + assertThat(sessionRegistry.find(targetContext.sessionId())).isPresent(); + scenario.actor().sendLine("TELL Sora Meet me at the forge"); - assertThat(scenario.actor().readLineContaining("ERROR COMMUNICATION_NOT_DELIVERED")) - .contains("ERROR COMMUNICATION_NOT_DELIVERED", "Sender Account identity unavailable"); - assertThat(socialStub().lastRequest()).isEmpty(); - assertThat( - buffers - .get(target.tenantId(), target.gameInstanceId(), target.characterId()) - .map( - screen -> - screen.entries().stream() - .filter(entry -> !"look_view".equals(entry.payloadType())) - .toList())) - .isEqualTo(targetBefore); + GameplayAsyncAssertions.assertBufferedScreenEventuallyContains( + screenBufferService, + targetContext, + COMMAND_WAIT, + ChatTestFixtures.canonicalTellTargetText()); + assertThat(scenario.actor().readLineContaining(ChatTestFixtures.canonicalTellText())) + .contains(ChatTestFixtures.canonicalTellText()); + assertThat(scenario.target().readLineContaining(ChatTestFixtures.canonicalTellTargetText())) + .contains(ChatTestFixtures.canonicalTellTargetText()); } } - private static void assertNoItemMutationRequests() { - assertThat(entityStub().lastPickupRequest()).isEmpty(); - assertThat(entityStub().lastDropRequest()).isEmpty(); - assertThat(entityStub().lastPutRequest()).isEmpty(); - assertThat(entityStub().lastTakeRequest()).isEmpty(); - } - private static synchronized void ensureTestServicesStarted() { if (STACK != null && GATEWAY != null) { return; @@ -732,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) {