diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 0a09c53a57..9f0a4fe06a 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -62,7 +62,7 @@ The hosted Creator Party, terms catalog, acceptance/currentness evidence, and ch `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; the canonical target portable-data export lifecycle 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/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration now creates only global Account state and its platform audit outbox row; it 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. On connect-token cache misses and text `PLAY`, consumers currently proceed only when `membershipExists` and `gameplayAdmissionAllowed` are true; they do not enforce the emitted `membershipLifecycleState` or `membershipAuthorityGeneration`. Cached-success connect-token replay can return without fresh membership, entitlement, or pointer checks. For eligible public-production text `PLAY`, missing or existing non-admitting membership may currently produce `JOIN_REQUIRED`; when membership exists but gameplay admission is false, connect-token issuance instead returns `CONNECT_TOKEN_REJECTED`. On checked paths, consumers therefore do 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, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token 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. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so 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; its Account component exposes the persisted UUID, while profile fields retain their current identifiers. 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/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration returns the persisted Account UUID in `AccountDto.id` / `CreateAccountResponse.account_id` 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. On connect-token cache misses and text `PLAY`, consumers currently proceed only when `membershipExists` and `gameplayAdmissionAllowed` are true; they do not enforce the emitted `membershipLifecycleState` or `membershipAuthorityGeneration`. Cached-success connect-token replay can return without fresh membership, entitlement, or pointer checks. For eligible public-production text `PLAY`, missing or existing non-admitting membership may currently produce `JOIN_REQUIRED`; when membership exists but gameplay admission is false, connect-token issuance instead returns `CONNECT_TOKEN_REJECTED`. On checked paths, consumers therefore do 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, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token 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. Current login/auth/bootstrap results and tenant/profile/member DTOs still use numeric account and tenant identities; only registration and the Account components of the existing Account-local exports now use Account UUID. 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. ### Current vs Target Export Lifecycle @@ -77,7 +77,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu `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. - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `account_service.proto`. -- `CreateAccount` – registers a global Account identity and returns its `accountId`; it does not select a tenant or create membership/profile state. Registration also appends a platform-scoped audit outbox record in the Account transaction. +- `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. - `Authenticate` – verifies one account-selected ordinary credential mode, either `PASSWORD` or verified-email `EMAIL_OTP`, using a required, typed `CredentialSourceContext` and, only for the approved Game Session-to-Account control path, issues the receiver-specific private `game-session-account-delegation` JWT with exact audience `account-service`. Gameplay credential and email-code authentication are global Account-identity operations: their current wire requests reserve the former `tenant_id` fields, and Account neither selects nor requires membership before returning identity. The pre-v1 wire convergence also reserves the former `username` field number and places `email` on a new field number, so mixed old/new Account and Game Session versions fail closed instead of reinterpreting identifiers; the two services must be deployed as one compatibility cohort for uninterrupted gameplay login. The target registry-backed flow stores one `session:auth:token:` record; current gameplay issuance uses the legacy account-scoped session key and defers tenant membership/grant/entitlement to `JOIN`/`PLAY`. Generic `Service JWT` and `aud=internal` profiles are forbidden; workload-only authorization uses mTLS. The context contains a server-derived canonical client address and transport class; Account rejects absent or untrusted context in player-facing environments, and public callers cannot assert it. - `JoinPublicProductionMembership` – implemented local internal Account RPC for explicit public-production membership creation/restoration. It accepts the Account-issued `connectScopeId`, operation `requestId`, and authenticated caller context; it revalidates the exact stored target and fresh `allowPublicJoin` entitlement evidence, binds a v1 digest to that caller/scope/policy snapshot, and commits membership/version, durable operation outcome, and tenant audit outbox evidence together. The digest's canonical grammar remains owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). A `PENDING` operation after an unknown database commit outcome still requires recovery/reconciliation implementation and exact-final-head PostgreSQL proof; no implicit membership writer or production end-to-end completion is claimed. @@ -207,7 +207,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 current executable REST and internal response examples use numeric account and tenant IDs. UUID wire identities are an ADR 0020 target-state migration and are not current executable examples. +Current authentication, profile, membership, and tenant response examples retain numeric identifiers. Registration `AccountDto.id` and the Account component of the existing Account-local exports carry canonical Account UUIDs; profile and tenant identifiers in those exports remain unchanged. This bounded output change does not claim full portable export or complete ADR 0020 wire migration. Canonical current `/auth/login` success shape: diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 363558cf58..4d7a172fd7 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,7 +8,7 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status -Account V29 now persists an immutable, unique, non-nil `account_uuid` with provenance and the unchanged numeric source-row id. The repository writes or reads back that identity for Account rows. This is a storage prerequisite only: REST/gRPC authentication outputs and downstream session carriers do not yet use the UUID. Focused repository and retained-row migration integration cases are present, but local PostgreSQL execution is unavailable while Docker is disabled; [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. +Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST/gRPC and the Account component of the current Account/profile-local and legacy tenant exports expose that persisted UUID through `AccountDto.id`; the mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and new registration audit payloads use the same UUID. Profile and tenant DTO identifiers, authentication results, JWT subjects, and downstream consumers remain unchanged; the current export is still partial Account/profile-local data, not the canonical portable export. The Account-local UUID-to-row resolver also remains confined to Account. The closed consumer boundary is incomplete: shared `SessionContext.currentAccountIdOrNull()` still requires numeric claims and is used by `GrpcClientAuth`, Logging & Admin `SessionActorReaders`, Automation Scripting `ScriptEventIngressServiceImpl`, and Social & Groups current-account authorization; Game Session control-plane owner authorization also compares numeric owner IDs. These consumers are outside this Account-owned slice, so no UUID-authentication or downstream-consumer proof is claimed. Focused repository and retained-row migration integration cases are present, but local PostgreSQL execution is unavailable while Docker is disabled; [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. 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 successful deletion immediately removes Account-owned rows including payment transactions. Those behaviors directly conflict with [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and the bounded erasure workflow below. @@ -59,7 +59,7 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi ## 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. This is Account-local storage identity only; authentication outputs and downstream session carriers do not yet use the UUID. +- `account` table stores username, password hash, email, and status flags for the global platform account, with an immutable unique non-nil `account_uuid`, its provenance, and the unchanged numeric source-row id added by V29. The numeric source-row id remains Account-local; registration and the Account portion of current Account-local exports expose the UUID as described in [Account API Contracts](./api-contracts.md). Authentication outputs and downstream session carriers do not yet use the UUID. - 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/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 073661d170..af40c9fcbb 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,7 +10,7 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: -- Game Session V11 adds nullable `gameplay_command.account_uuid` storage and repository round-trip mapping alongside the retained numeric `account_id`. Historical commands remain without an inferred UUID, and no producer or session carrier supplies or consumes this field yet; opaque internal carrier preparation and its retained-record/proof limits are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). The focused migration and repository PostgreSQL cases are present but skip locally while Docker is disabled; Account UUID ownership remains in [Account Runtime and Data](../account-service/runtime-and-data.md) under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). +- Game Session V11 adds nullable `gameplay_command.account_uuid` storage and repository round-trip mapping alongside the retained numeric `account_id`. Historical commands remain without an inferred UUID, and no producer or session carrier supplies or consumes this field yet; prepared `String` account-identity carriers still contain numeric row-id text and do not prove UUID consumption. Opaque internal carrier preparation and its retained-record/proof limits are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). The focused migration and repository PostgreSQL cases are present but skip locally while Docker is disabled; Account UUID ownership remains in [Account Runtime and Data](../account-service/runtime-and-data.md) under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). - The current effective-settings HTTP read is admitted by the service-wide `PRIVILEGED` role requirement, whose shared classifier accepts any global privileged role or any tenant-scoped `tenantAdmin`/`moderator` claim. `EffectiveSettingsController` then trusts query tenant/game selectors and session ids: it can synthesize a requested tenant scope without binding it to the caller's scoped role, or resolve a persisted session without checking that its tenant is authorized by the caller. The current controller/integration tests do not prove denial of a tenant-A caller reading tenant-B settings. - **Target effective-settings boundary:** keep this as a read-only operator surface but make authorization route-aware. Bind a tenant-scoped role to the exact target tenant and require persisted session tenant ownership/equality; allow a global `platformAdmin` branch to select a tenant only with current operator authorization, target-tenant generation, and `privileged_control`. Reject ambiguous/missing target authority, tenant/session mismatches, and unavailable owner/session evidence before invoking any resolver. The negative proof must cover scoped cross-tenant synthetic and persisted-session reads and the global branch without privileged control. 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 d758ce8d00..b3eeb9354c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The storage-only UUID prerequisite now persists Account-owned immutable UUID identity with provenance at Account, and adds nullable Account UUID evidence to the Game Session command ledger while preserving retained numeric Account IDs. Internal carrier types are prepared separately as recorded below, but no producer or consumer supplies or consumes canonical Account UUID values; UUID authentication outputs, JWTs, `PLAY`, and Entity Management remain unactivated. The focused PostgreSQL migration and repository cases are present but were skipped locally because Docker is disabled; `AA-1.1` and `AA-2.1` remain `partial` / `drift-found`, with no runtime-proof upgrade. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md), [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md), and [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md). +Account's persisted UUID now backs registration REST/gRPC output and the Account component of its existing Account/profile-local and legacy tenant exports. The canonical mapper rejects missing, nil, unprovenanced, or source-row-mismatched identity; registration audit uses the exact same UUID. The Account-local UUID-to-row resolver remains within Account. Authentication results and JWTs, profile and tenant DTO identity fields, Game Session carriers, `PLAY`, and Entity Management remain outside this output slice. Numeric Account-claim consumers remain outside this slice in common-security `GrpcClientAuth`, Logging & Admin `SessionActorReaders`, Automation Scripting `ScriptEventIngressServiceImpl`, Social & Groups current-account authorization, and Game Session's numeric control-plane owner authorization. The focused PostgreSQL migration and repository cases are present but were skipped locally because Docker is disabled; `AA-1.1` and `AA-2.1` remain `partial` / `drift-found`, with no UUID-authentication or downstream runtime-proof upgrade. The local export remains partial Account/profile data, not a full portable export. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md), [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md), and [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md). Internal Account-carrier typing is prepared in Game Session, while current producers, JWT claims/parsers, and numeric-only collaborators remain unchanged. This does not activate canonical Account UUID authentication or Entity roster/entry behavior and does not backfill historical command UUIDs; canonical identity/namespace targets remain [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), and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). Focused unit proof covers fail-closed first-party retained-context lookup, unreadable presence lookup without index pruning, and bounded pre-mutation rejection of unreadable or wrong-type presence values for removal, AFK/activity updates, and registration. `RedisSessionContextService` mutation reads still expose raw `SerializationException`; mocked tests show unreadable session-alias reads abort before writes/deletes, but mixed-binary behavior, same-session-ID reauthentication/recovery, live Redis/runtime, and fresh-image proof remain unproved. #2898 is not fixed by this preparation. @@ -33,7 +33,7 @@ These links add decision provenance only; they do not upgrade player-access or s | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [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); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` now persist or read back an immutable, unique, non-nil Account UUID with provenance while retaining the numeric source-row id, as required by ADR 0020. Focused PostgreSQL repository and retained-row migration cases are present but skipped locally because Docker is disabled; deployment retained-row disposition/readback remains open. This UUID is storage-only and is not yet used in authentication outputs or downstream session carriers. Current registration creates global Account identity plus platform audit outbox evidence only; it does not create a tenant membership or profile, and legacy tenant input is not authority. The current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication establish global account identity without selecting a tenant or requiring current membership; successful sessions are account-scoped. Lifecycle-state retention is tracked under AA-1.3. | +| `AA-1.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); [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); [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. 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); [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) | [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) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, 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. 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 text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, 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. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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. | diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index b6ea879e90..ff20d2c324 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -97,7 +97,7 @@ message CreateAccountRequest { // Result of a CreateAccount call. message CreateAccountResponse { - // Unique identifier of the newly created account. + // Canonical non-nil Account UUID of the newly created account. string account_id = 1; // Details about why the creation failed, if applicable. shared.v1.ErrorDetail error = 2; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java index ed43a78720..3636796911 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java @@ -5,7 +5,7 @@ import jakarta.validation.constraints.Size; public record AccountDto( - Long id, + String id, @NotNull @Size(max = 50) String username, @NotNull @Email @Size(max = 100) String email, @Size(max = 20) String role, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java index 0b3fb0906b..23b484444f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java @@ -2,12 +2,32 @@ import net.firedevops.firemud.accountservice.dto.AccountDto; import net.firedevops.firemud.accountservice.entity.Account; +import org.mapstruct.AfterMapping; import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.MappingTarget; import org.mapstruct.ReportingPolicy; @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) public interface AccountMapper { + @Mapping(target = "id", source = "accountUuid") AccountDto toDto(Account entity); - Account toEntity(AccountDto dto); + @AfterMapping + default void requireExactPersistedIdentity(Account entity, @MappingTarget AccountDto accountDto) { + if (entity == null) { + return; + } + if (entity.getId() == null + || entity.getId() <= 0L + || entity.getAccountUuid() == null + || new java.util.UUID(0L, 0L).equals(entity.getAccountUuid()) + || entity.getAccountUuidProvenance() == null + || entity.getAccountUuidSourceNumericId() == null + || !entity.getId().equals(entity.getAccountUuidSourceNumericId()) + || !entity.getAccountUuid().toString().equals(accountDto.id())) { + throw new IllegalStateException( + "Account UUID readback did not match its exact persisted source row"); + } + } } 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 c3d2909abc..75f526cda4 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 @@ -1,5 +1,6 @@ package net.firedevops.firemud.accountservice.service; +import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountDataExportDto; import net.firedevops.firemud.accountservice.dto.AccountDto; import net.firedevops.firemud.accountservice.dto.AccountLoginAuthModesDto; @@ -64,6 +65,9 @@ JoinPublicProductionResult joinPublicProductionFromGameSession( RuntimeMembershipDto getTenantMembershipForRuntime( Long accountId, Long tenantId, String requestId); + /** Resolves the public Account UUID to its private numeric storage key inside Account only. */ + Long resolveAccountStorageId(UUID accountUuid); + 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 29b6201f11..10c949a303 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 @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.service.impl; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; @@ -67,6 +68,7 @@ public class AccountGrpcService extends AccountServiceGrpc.AccountServiceImplBas private static final int MAX_ACCOUNT_IDS_PER_REQUEST = 100; private static final String AUTHORITY_UNAVAILABLE_MESSAGE = "Account authority unavailable; retry later"; + private static final String ACCOUNT_CREATION_INTERNAL_ERROR_MESSAGE = "Account creation failed"; private final PingService pingService; private final AccountService accountService; private final MeterRegistry meterRegistry; @@ -278,7 +280,7 @@ public void createAccount( request.getUsername(), request.getEmail(), request.getPassword()); var account = accountService.createAccount(dto); CreateAccountResponse response = - CreateAccountResponse.newBuilder().setAccountId(account.id().toString()).build(); + CreateAccountResponse.newBuilder().setAccountId(account.id()).build(); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (AccountAlreadyExistsException ex) { @@ -299,6 +301,11 @@ public void createAccount( .setError(appError("CreateAccount", "INVALID_ARGUMENT", ex.getMessage())) .build()); responseObserver.onCompleted(); + } catch (IllegalStateException ex) { + responseObserver.onError( + Status.INTERNAL + .withDescription(ACCOUNT_CREATION_INTERNAL_ERROR_MESSAGE) + .asRuntimeException()); } } 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 d843608e32..dc74190fed 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 @@ -54,6 +54,7 @@ import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthMode; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; @@ -118,6 +119,7 @@ public class AccountServiceImpl implements AccountService { "Join the selected world before discovering characters"; private static final String GAMEPLAY_DELEGATION_AUDIENCE = "account-service"; private static final int EMAIL_LOGIN_OTP_MAX_ATTEMPTS = 5; + private static final UUID NIL_ACCOUNT_UUID = new UUID(0L, 0L); private static final SecureRandom EMAIL_LOGIN_OTP_RANDOM = new SecureRandom(); private static final JsonMapper AUDIT_JSON = JsonMapper.builder().build(); @@ -220,13 +222,14 @@ public AccountDto createAccount(CreateAccountRequest request) { } catch (IntegrityConstraintViolationException | DataIntegrityViolationException ex) { throw new AccountAlreadyExistsException(ex); } + AccountDto accountDto = accountMapper.toDto(saved); accountAuditOutboxRepository.append( UUID.randomUUID(), "platform", null, "ACCOUNT_REGISTERED", - "{\"accountId\":" + saved.getId() + "}"); - return accountMapper.toDto(saved); + "{\"accountId\":\"" + accountDto.id() + "\"}"); + return accountDto; } @Override @@ -1984,6 +1987,34 @@ private Account requireAccount(Long accountId) { .orElseThrow(() -> new IllegalArgumentException("Account not found")); } + /** Resolves a canonical public identity at the Account persistence boundary only. */ + @Override + @Transactional(readOnly = true) + public Long resolveAccountStorageId(UUID accountUuid) { + if (accountUuid == null || NIL_ACCOUNT_UUID.equals(accountUuid)) { + throw new IllegalArgumentException("A canonical non-nil Account UUID is required"); + } + Account account = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow(() -> new IllegalArgumentException("Account not found")); + AccountIdentityProvenance provenance = account.getAccountUuidProvenance(); + if (account.getId() == null + || account.getId() <= 0L + || account.getAccountUuid() == null + || NIL_ACCOUNT_UUID.equals(account.getAccountUuid()) + || account.getAccountUuidSourceNumericId() == null + || !account.getId().equals(account.getAccountUuidSourceNumericId()) + || (provenance != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + && provenance != AccountIdentityProvenance.ACCOUNT_V29_MIGRATION + && provenance != AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT) + || !accountUuid.equals(account.getAccountUuid())) { + throw new IllegalStateException( + "Account UUID readback did not match its exact persisted source row"); + } + return account.getId(); + } + private boolean hasRealmAccessGrant( Long accountId, Long tenantId, String worldSlug, String realmSlug) { return accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 8411c88db4..620742cab5 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -54,7 +54,9 @@ components: type: object properties: id: - type: integer + type: string + format: uuid + description: Canonical non-nil Account UUID; never the numeric database primary key. username: type: string email: 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 2207175c8b..ca7c8d7ec0 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 @@ -10,6 +10,7 @@ import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.HttpTestSupport; @@ -29,6 +30,7 @@ import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -60,6 +62,8 @@ static void configure(DynamicPropertyRegistry registry) { @LocalServerPort private int port; @Autowired private JwtUtil jwtUtil; @Autowired private DSLContext dsl; + @Autowired private AccountService accountService; + private final JsonMapper jsonMapper = JsonMapper.builder().build(); @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GameSessionClient gameSessionClient; @@ -92,9 +96,29 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); assertThat(response.statusCode()).isEqualTo(200); + String responseAccountUuid = + jsonMapper.readTree(response.body()).path("data").path("id").asText(null); + assertThat(responseAccountUuid).isNotBlank(); + UUID accountUuid = UUID.fromString(responseAccountUuid); Number accountId = dsl.resultQuery("SELECT id FROM accounts WHERE email = ?", email).fetchOne(0, Number.class); assertThat(accountId).isNotNull(); + assertThat(accountUuid) + .isEqualTo( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId.longValue()) + .fetchOne(0, UUID.class)); + assertThat( + dsl.resultQuery( + "SELECT account_uuid_source_numeric_id FROM accounts WHERE id = ?", + accountId.longValue()) + .fetchOne(0, Long.class)) + .isEqualTo(accountId.longValue()); + assertThat( + dsl.resultQuery( + "SELECT account_uuid_provenance FROM accounts WHERE id = ?", + accountId.longValue()) + .fetchOne(0, String.class)) + .isEqualTo("ACCOUNT_REPOSITORY_INSERT"); assertThat(dsl.fetchValue("SELECT tenant_id FROM accounts WHERE id = ?", accountId.longValue())) .isNull(); assertThat(dsl.fetchValue("SELECT role FROM accounts WHERE id = ?", accountId.longValue())) @@ -113,8 +137,24 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws "SELECT COUNT(*) FROM account_audit_outbox " + "WHERE scope = 'platform' AND tenant_id IS NULL " + "AND event_type = 'ACCOUNT_REGISTERED' AND payload = ?", - "{\"accountId\":" + accountId.longValue() + "}")) + "{\"accountId\":\"" + responseAccountUuid + "\"}")) .isEqualTo(1L); + + var accountExport = accountService.exportAccountData(accountId.longValue()); + assertThat(accountExport.account().id()).isEqualTo(responseAccountUuid); + assertThat(accountExport.profiles()).isEmpty(); + + dsl.execute( + "INSERT INTO account_tenant_membership (account_id, tenant_id, lifecycle_state, " + + "gameplay_admission_allowed, membership_version, " + + "membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, 'LEGACY_UNVERIFIED', FALSE, 1, 1, 'LEGACY_UNVERIFIED')", + accountId.longValue(), + 999L); + var tenantExport = accountService.exportTenantData(999L, accountId.longValue()); + assertThat(tenantExport.account().id()).isEqualTo(responseAccountUuid); + assertThat(tenantExport.tenantId()).isEqualTo(999L); + assertThat(tenantExport.profile()).isNull(); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java index 20010b7bb1..616ff0fbc1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java @@ -67,7 +67,9 @@ void clear() { @Test void createAccountReturnsDto() throws Exception { CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "password"); - AccountDto response = new AccountDto(1L, "demo", "demo@example.com", "player", true); + AccountDto response = + new AccountDto( + "4cae05e8-7a6b-4b14-9d44-665e3eec450b", "demo", "demo@example.com", "player", true); when(accountService.createAccount(request)).thenReturn(response); mockMvc @@ -77,6 +79,7 @@ void createAccountReturnsDto() throws Exception { .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) + .andExpect(jsonPath("$.data.id").value("4cae05e8-7a6b-4b14-9d44-665e3eec450b")) .andExpect(jsonPath("$.data.username").value("demo")); } @@ -135,7 +138,9 @@ void deleteAccountRejectsScopedTenantAdminBecauseFullDeletionIsAccountScoped() t @Test void exportAccountAllowsCurrentAccountWithoutTenantScope() throws Exception { - AccountDto account = new AccountDto(42L, "demo", "demo@example.com", "player", true); + AccountDto account = + new AccountDto( + "4cae05e8-7a6b-4b14-9d44-665e3eec450b", "demo", "demo@example.com", "player", true); when(accountService.exportAccountData(42L)) .thenReturn(new AccountDataExportDto(account, List.of())); String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); @@ -148,7 +153,9 @@ void exportAccountAllowsCurrentAccountWithoutTenantScope() throws Exception { @Test void exportTenantDataAllowsScopedTenantRole() throws Exception { - AccountDto account = new AccountDto(42L, "demo", "demo@example.com", "player", true); + AccountDto account = + new AccountDto( + "4cae05e8-7a6b-4b14-9d44-665e3eec450b", "demo", "demo@example.com", "player", true); when(accountService.exportTenantData(7L, 42L)) .thenReturn(new TenantDataExportDto(7L, account, null)); String token = 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 fda8d4325e..f6dfd7e760 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 @@ -58,7 +58,13 @@ void accountCreationRemainsPublicInProdProfile() throws Exception { CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "swordfish"); when(accountService.createAccount(request)) - .thenReturn(new AccountDto(1L, "demo", "demo@example.com", "player", true)); + .thenReturn( + new AccountDto( + "4cae05e8-7a6b-4b14-9d44-665e3eec450b", + "demo", + "demo@example.com", + "player", + true)); mockMvc .perform( @@ -67,7 +73,7 @@ void accountCreationRemainsPublicInProdProfile() throws Exception { .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.id").value(1)) + .andExpect(jsonPath("$.data.id").value("4cae05e8-7a6b-4b14-9d44-665e3eec450b")) .andExpect(jsonPath("$.data.username").value("demo")); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/mapper/AccountMapperTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/mapper/AccountMapperTest.java new file mode 100644 index 0000000000..228f3bb95a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/mapper/AccountMapperTest.java @@ -0,0 +1,84 @@ +package net.firedevops.firemud.accountservice.mapper; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountDto; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.mapstruct.factory.Mappers; + +class AccountMapperTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private final AccountMapper mapper = Mappers.getMapper(AccountMapper.class); + + @ParameterizedTest + @EnumSource(AccountIdentityProvenance.class) + void mapsCanonicalUuidForEverySupportedProvenance(AccountIdentityProvenance provenance) { + Account account = account(42L, ACCOUNT_UUID, provenance, 42L); + + AccountDto result = mapper.toDto(account); + + assertEquals(ACCOUNT_UUID.toString(), result.id()); + } + + @Test + void rejectsMissingUuidInsteadOfFallingBackToNumericRowId() { + assertRejected(account(42L, null, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, 42L)); + } + + @Test + void rejectsNilUuid() { + assertRejected( + account(42L, new UUID(0L, 0L), AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, 42L)); + } + + @Test + void rejectsMissingProvenance() { + assertRejected(account(42L, ACCOUNT_UUID, null, 42L)); + } + + @ParameterizedTest + @NullSource + @ValueSource(longs = {0L, -1L}) + void rejectsMissingOrNonpositiveSourceRow(Long accountId) { + assertRejected( + account( + accountId, + ACCOUNT_UUID, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, + accountId)); + } + + @Test + void rejectsMissingSourceNumericId() { + assertRejected( + account(42L, ACCOUNT_UUID, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, null)); + } + + @Test + void rejectsSourceNumericIdThatDoesNotMatchTheAccountRow() { + assertRejected( + account(42L, ACCOUNT_UUID, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, 43L)); + } + + private void assertRejected(Account account) { + assertThrows(IllegalStateException.class, () -> mapper.toDto(account)); + } + + private Account account( + Long id, UUID accountUuid, AccountIdentityProvenance provenance, Long sourceNumericId) { + Account account = new Account(); + account.setId(id); + account.setAccountUuid(accountUuid); + account.setAccountUuidProvenance(provenance); + account.setAccountUuidSourceNumericId(sourceNumericId); + return account; + } +} 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 0db02b400a..879fb785b7 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 @@ -6,10 +6,12 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import io.grpc.Context; +import io.grpc.Status; import io.grpc.stub.StreamObserver; 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 net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateRequest; @@ -665,12 +667,62 @@ void createAccountConflictReturnsApplicationError() { assertFalse(observer.receivedTransportError()); } + @Test + void createAccountInternalFailureReturnsBoundedTransportError() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.createAccount(Mockito.any())) + .thenThrow(new IllegalStateException("private backend detail")); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AtomicInteger nextCalls = new AtomicInteger(); + AtomicInteger errorCalls = new AtomicInteger(); + AtomicInteger completedCalls = new AtomicInteger(); + AtomicReference transportError = new AtomicReference<>(); + + service.createAccount( + CreateAccountRequest.newBuilder() + .setUsername("demo") + .setEmail("demo@example.com") + .setPassword("pass") + .build(), + new StreamObserver() { + @Override + public void onNext(CreateAccountResponse value) { + nextCalls.incrementAndGet(); + } + + @Override + public void onError(Throwable throwable) { + errorCalls.incrementAndGet(); + transportError.set(throwable); + } + + @Override + public void onCompleted() { + completedCalls.incrementAndGet(); + } + }); + + assertEquals(0, nextCalls.get()); + assertEquals(1, errorCalls.get()); + assertEquals(0, completedCalls.get()); + assertEquals(Status.Code.INTERNAL, Status.fromThrowable(transportError.get()).getCode()); + assertEquals( + "Account creation failed", Status.fromThrowable(transportError.get()).getDescription()); + assertFalse( + Status.fromThrowable(transportError.get()) + .getDescription() + .contains("private backend detail")); + } + @Test void createAccountReturnsAccountIdForGlobalRequest() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.createAccount(Mockito.any())) - .thenReturn(new AccountDto(1L, "demo", "e@example.com", "player", true)); + .thenReturn( + new AccountDto( + "4cae05e8-7a6b-4b14-9d44-665e3eec450b", "demo", "e@example.com", "player", true)); AccountGrpcService service = new AccountGrpcService(pingService, accountService); AtomicReference ref = new AtomicReference<>(); @@ -694,7 +746,7 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("1", ref.get().getAccountId()); + assertEquals("4cae05e8-7a6b-4b14-9d44-665e3eec450b", ref.get().getAccountId()); org.mockito.ArgumentCaptor captor = org.mockito.ArgumentCaptor.forClass( 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 2b3aa8aa5d..7f579f6040 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 @@ -40,6 +40,7 @@ import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthMode; import net.firedevops.firemud.accountservice.entity.AccountRealmAccessGrant; @@ -232,21 +233,140 @@ void setup() { transactionManager); } + @ParameterizedTest + @EnumSource(AccountIdentityProvenance.class) + void resolvesAccountUuidToPrivateStorageIdForEachSupportedProvenance( + AccountIdentityProvenance provenance) { + UUID accountUuid = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + Account account = new Account(); + account.setId(42L); + account.setAccountUuid(accountUuid); + account.setAccountUuidProvenance(provenance); + account.setAccountUuidSourceNumericId(42L); + when(accountRepository.findByAccountUuid(accountUuid)).thenReturn(Optional.of(account)); + + assertEquals(42L, service.resolveAccountStorageId(accountUuid)); + org.mockito.Mockito.verify(accountRepository).findByAccountUuid(accountUuid); + } + + @Test + void rejectsNullAccountUuidBeforeResolvingPrivateStorageId() { + assertThrows(IllegalArgumentException.class, () -> service.resolveAccountStorageId(null)); + verifyNoInteractions(accountRepository); + } + + @Test + void rejectsNilAccountUuidBeforeResolvingPrivateStorageId() { + UUID nilUuid = new UUID(0L, 0L); + + assertThrows(IllegalArgumentException.class, () -> service.resolveAccountStorageId(nilUuid)); + verifyNoInteractions(accountRepository); + } + + @Test + void rejectsAccountUuidWithoutPersistedAccountRow() { + UUID accountUuid = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + when(accountRepository.findByAccountUuid(accountUuid)).thenReturn(Optional.empty()); + + assertThrows( + IllegalArgumentException.class, () -> service.resolveAccountStorageId(accountUuid)); + } + + @Test + void rejectsAccountUuidMappingWhenReturnedRowHasDifferentUuid() { + UUID requestedUuid = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + Account account = new Account(); + account.setId(42L); + account.setAccountUuid(UUID.fromString("b45dc804-6626-48e4-a657-4a8dfc4e9203")); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + account.setAccountUuidSourceNumericId(42L); + when(accountRepository.findByAccountUuid(requestedUuid)).thenReturn(Optional.of(account)); + + assertThrows(IllegalStateException.class, () -> service.resolveAccountStorageId(requestedUuid)); + } + + @Test + void rejectsAccountUuidMappingWithoutPrivateStorageRowId() { + UUID accountUuid = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + Account account = new Account(); + account.setAccountUuid(accountUuid); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + account.setAccountUuidSourceNumericId(42L); + when(accountRepository.findByAccountUuid(accountUuid)).thenReturn(Optional.of(account)); + + assertThrows(IllegalStateException.class, () -> service.resolveAccountStorageId(accountUuid)); + } + + @ParameterizedTest + @ValueSource(longs = {0L, -1L}) + void rejectsAccountUuidMappingWithInvalidPrivateStorageRowId(long accountId) { + UUID accountUuid = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + Account account = new Account(); + account.setId(accountId); + account.setAccountUuid(accountUuid); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + account.setAccountUuidSourceNumericId(accountId); + when(accountRepository.findByAccountUuid(accountUuid)).thenReturn(Optional.of(account)); + + assertThrows(IllegalStateException.class, () -> service.resolveAccountStorageId(accountUuid)); + } + + @Test + void rejectsAccountUuidMappingWithoutPrivateSourceNumericId() { + UUID accountUuid = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + Account account = new Account(); + account.setId(42L); + account.setAccountUuid(accountUuid); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + when(accountRepository.findByAccountUuid(accountUuid)).thenReturn(Optional.of(account)); + + assertThrows(IllegalStateException.class, () -> service.resolveAccountStorageId(accountUuid)); + } + + @Test + void rejectsAccountUuidMappingWhoseProvenanceSourceDoesNotMatchTheRow() { + UUID accountUuid = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + Account account = new Account(); + account.setId(42L); + account.setAccountUuid(accountUuid); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_V29_MIGRATION); + account.setAccountUuidSourceNumericId(43L); + when(accountRepository.findByAccountUuid(accountUuid)).thenReturn(Optional.of(account)); + + assertThrows(IllegalStateException.class, () -> service.resolveAccountStorageId(accountUuid)); + } + + @Test + void rejectsAccountUuidMappingWithoutRecognizedProvenance() { + UUID accountUuid = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + Account account = new Account(); + account.setId(42L); + account.setAccountUuid(accountUuid); + account.setAccountUuidSourceNumericId(42L); + when(accountRepository.findByAccountUuid(accountUuid)).thenReturn(Optional.of(account)); + + assertThrows(IllegalStateException.class, () -> service.resolveAccountStorageId(accountUuid)); + } + @Test void createAccountPersistsOnlyGlobalIdentity() { CreateAccountRequest request = new CreateAccountRequest("demo", " DEMO@example.com ", "password"); + UUID accountUuid = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) .thenAnswer( invocation -> { Account saved = invocation.getArgument(0); saved.setId(1L); + saved.setAccountUuid(accountUuid); + saved.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + saved.setAccountUuidSourceNumericId(1L); return saved; }); AccountDto dto = service.createAccount(request); - assertEquals(1L, dto.id()); + assertEquals(accountUuid.toString(), dto.id()); assertEquals("demo", dto.username()); org.mockito.ArgumentCaptor accountCaptor = org.mockito.ArgumentCaptor.forClass(Account.class); @@ -258,11 +378,34 @@ void createAccountPersistsOnlyGlobalIdentity() { org.mockito.ArgumentMatchers.eq("platform"), org.mockito.ArgumentMatchers.isNull(), org.mockito.ArgumentMatchers.eq("ACCOUNT_REGISTERED"), - org.mockito.ArgumentMatchers.eq("{\"accountId\":1}")); + org.mockito.ArgumentMatchers.eq("{\"accountId\":\"" + accountUuid + "\"}")); assertEquals(null, accountCaptor.getValue().getRole()); verifyNoInteractions(profileRepository, accountTenantMembershipRepository); } + @Test + void createAccountRejectsPublicIdentityWithoutExactPersistedSourceRow() { + when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) + .thenAnswer( + invocation -> { + Account saved = invocation.getArgument(0); + saved.setId(1L); + saved.setAccountUuid(UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b")); + saved.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + saved.setAccountUuidSourceNumericId(2L); + return saved; + }); + + assertThrows( + IllegalStateException.class, + () -> + service.createAccount( + new CreateAccountRequest("demo", "demo@example.com", "password"))); + + verifyNoInteractions( + accountAuditOutboxRepository, profileRepository, accountTenantMembershipRepository); + } + @Test void createAccountReturnsExplicitConflictForCanonicalIdentityCollision() { CreateAccountRequest request = @@ -5371,6 +5514,9 @@ void updateProfileRejectsReservedHiddenStaffPolicyBeforePersistence() { void exportAccountDataIncludesProfilesAcrossTenants() { Account account = new Account(); account.setId(2L); + account.setAccountUuid(UUID.fromString("d09f80cb-a46a-415e-8d35-c9e8068e49de")); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_V29_MIGRATION); + account.setAccountUuidSourceNumericId(2L); account.setUsername("demo"); account.setEmail("demo@example.com"); Profile tenantOne = profile(account, 1L, "one"); @@ -5388,7 +5534,7 @@ void exportAccountDataIncludesProfilesAcrossTenants() { var export = service.exportAccountData(2L); - assertEquals(2L, export.account().id()); + assertEquals("d09f80cb-a46a-415e-8d35-c9e8068e49de", export.account().id()); assertEquals(2, export.profiles().size()); } @@ -5405,6 +5551,26 @@ void exportTenantDataRequiresTenantMembershipOrProfile() { assertThrows(IllegalArgumentException.class, () -> service.exportTenantData(7L, 2L)); } + @Test + void exportTenantDataUsesPublicAccountUuidAndRetainsTenantLocalFields() { + Account account = new Account(); + account.setId(2L); + account.setAccountUuid(UUID.fromString("d09f80cb-a46a-415e-8d35-c9e8068e49de")); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_V29_MIGRATION); + account.setAccountUuidSourceNumericId(2L); + account.setUsername("demo"); + account.setEmail("demo@example.com"); + when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); + when(profileRepository.findByAccountIdAndTenantId(2L, 7L)).thenReturn(Optional.empty()); + when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 7L)).thenReturn(true); + + var export = service.exportTenantData(7L, 2L); + + assertEquals("d09f80cb-a46a-415e-8d35-c9e8068e49de", export.account().id()); + assertEquals(7L, export.tenantId()); + assertNull(export.profile()); + } + @Test void deleteAccountRefusesNonterminalSubscription() { Account account = new Account();