diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 5eddf58fc7..363558cf58 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ 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. + 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. Account V22/V23 rewrite retained email values to canonical form and validate a canonical-email check, but compatibility with older binaries is unproved; the retained-data and rollout proof gap is tracked in [Shared Runtime Contracts and Persistence](../../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#unit-5b-persistence-review-consequences). @@ -57,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. +- `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. - 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 c4e61237ca..c446f74d01 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,6 +10,8 @@ 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. 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. - Script pin/epoch rollout remains partial: the authoritative `{scriptPatchVersion, scriptPinEpoch, controlPlaneRequestId}` owner read, CAS-backed pin transition, and instance-bound Automation admission epoch validation are live. Local instance-scoped Automation admission, duplicate replay, durable tick staging/replay, and final Game Session execution now compare the complete tuple; the live ledger is still limited to current atomic request/result rows, and bounded rollout-history readback plus complete source/target remote command identity and final-effect fencing remain gaps. See the [canonical runtime-execution owner](../../system-architecture-scripting-runtime-execution.md#normative-target-contract) and the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). 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 9597372f71..7225438ac3 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ 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. It does not activate UUID authentication outputs, JWTs, session context, `PLAY`, Entity Management, or any producer/consumer carrier. 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). + Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, the Account-local explicit public-production JOIN writer and durable audit outbox/producer retry path, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` controller/operation exists locally, while the current Gateway guard still blocks external exposure; Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. @@ -29,12 +31,12 @@ 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) | [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); [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) | [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) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | 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. Source covers the zero-membership/profile registration boundary, but PostgreSQL runtime proof and deployment retained-row disposition/readback remain open. 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); [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.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. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; a same-account/same-tenant relogin may preserve its candidate binding for fresh admission checks, while a tenant switch clears the prior gameplay presence before saving the new context. Text `PLAY` performs Account membership/entitlement evaluation before strict persisted actor selection; focused service proof covers the Game Session-to-Entity peer allowlist. Connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. Account's local `JoinPublicProductionMembership` writer is implemented, but Game Session text `JOIN`/`Join & Play` dispatch remains unimplemented under #2898 and external exposure of the Account bootstrap route remains blocked. The strict ADR 0025 commit fence and membership-authority-generation reread at issuance remain incomplete; unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Generic prompt-mode login, deployment/mTLS, and fresh-image proof for the focused `PLAY` changes also remain incomplete. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.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) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [GameplayCommandRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [V11__gameplay_command_account_uuid.sql](../../../services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayCommandRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java); [GameplayCommandAccountUuidMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. V11 adds nullable Account UUID evidence to the Game Session command ledger and repository round-trip mapping while preserving retained numeric Account IDs; focused repository and migration PostgreSQL cases are present but skipped locally because Docker is disabled. No producer or session carrier supplies or consumes this field, and UUID storage does not activate UUID authentication, JWTs, session context, or `PLAY`. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; a same-account/same-tenant relogin may preserve its candidate binding for fresh admission checks, while a tenant switch clears the prior gameplay presence before saving the new context. Text `PLAY` performs Account membership/entitlement evaluation before strict persisted actor selection; focused service proof covers the Game Session-to-Entity peer allowlist. Connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. Account's local `JoinPublicProductionMembership` writer is implemented, but Game Session text `JOIN`/`Join & Play` dispatch remains unimplemented under #2898 and external exposure of the Account bootstrap route remains blocked. The strict ADR 0025 commit fence and membership-authority-generation reread at issuance remain incomplete; unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Generic prompt-mode login, deployment/mTLS, and fresh-image proof for the focused `PLAY` changes also remain incomplete. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java index 2fb0e62afe..09ed06a6b5 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Account.java @@ -1,10 +1,14 @@ package net.firedevops.firemud.accountservice.entity; +import java.util.UUID; import lombok.Data; @Data public class Account { private Long id; + private UUID accountUuid; + private AccountIdentityProvenance accountUuidProvenance; + private Long accountUuidSourceNumericId; private String username; private String email; private String passwordHash; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java new file mode 100644 index 0000000000..f3f17c8704 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java @@ -0,0 +1,18 @@ +package net.firedevops.firemud.accountservice.entity; + +public enum AccountIdentityProvenance { + ACCOUNT_V29_MIGRATION, + ACCOUNT_REPOSITORY_INSERT, + ACCOUNT_DATABASE_INSERT; + + public static AccountIdentityProvenance fromStorageValue(String value) { + if (value == null) { + throw new IllegalStateException("Account UUID provenance must not be null"); + } + try { + return AccountIdentityProvenance.valueOf(value); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Unknown Account UUID provenance: " + value, exception); + } + } +} 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 dbc73e32ab..037cd63da3 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,8 +3,11 @@ import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNTS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.jooq.tables.records.AccountsRecord; import net.firedevops.firemud.common.EmailCanonicalization; import org.jooq.DSLContext; @@ -26,6 +29,14 @@ public Optional findById(Long id) { dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(id)).fetchOne(this::toEntity)); } + public Optional findByAccountUuid(UUID accountUuid) { + Objects.requireNonNull(accountUuid, "accountUuid must not be null"); + return Optional.ofNullable( + dsl.selectFrom(ACCOUNTS) + .where(ACCOUNTS.ACCOUNT_UUID.eq(accountUuid)) + .fetchOne(this::toEntity)); + } + public Optional findByUsername(String username) { return Optional.ofNullable( dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.USERNAME.eq(username)).fetchOne(this::toEntity)); @@ -41,8 +52,13 @@ public Optional findByEmail(String email) { public Account save(Account entity) { entity.setEmail(EmailCanonicalization.normalize(entity.getEmail())); if (entity.getId() == null) { - Long id = + UUID expectedUuid = UUID.randomUUID(); + AccountsRecord inserted = dsl.insertInto(ACCOUNTS) + .set(ACCOUNTS.ACCOUNT_UUID, expectedUuid) + .set( + ACCOUNTS.ACCOUNT_UUID_PROVENANCE, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.name()) .set(ACCOUNTS.USERNAME, entity.getUsername()) .set(ACCOUNTS.EMAIL, entity.getEmail()) .set(ACCOUNTS.PASSWORD_HASH, entity.getPasswordHash()) @@ -50,12 +66,20 @@ public Account save(Account entity) { .set(ACCOUNTS.EMAIL_VERIFIED, entity.isEmailVerified()) .set(ACCOUNTS.LOGIN_AUTH_MODES, normalizedLoginAuthModes(entity)) .set(ACCOUNTS.LIFECYCLE_STATE, entity.getLifecycleState().storageValue()) - .returningResult(ACCOUNTS.ID) - .fetchOne(ACCOUNTS.ID); - entity.setId(id); + .returning() + .fetchOne(); + if (inserted == null) { + throw new IllegalStateException("Account insert did not return its persisted identity"); + } + requireExactIdentityReadback( + inserted, expectedUuid, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + copyIdentityToEntity(entity, inserted); return entity; } - int updated = + UUID expectedUuid = entity.getAccountUuid(); + AccountIdentityProvenance expectedProvenance = entity.getAccountUuidProvenance(); + Long expectedSourceNumericId = entity.getAccountUuidSourceNumericId(); + var update = dsl.update(ACCOUNTS) .set(ACCOUNTS.USERNAME, entity.getUsername()) .set(ACCOUNTS.EMAIL, entity.getEmail()) @@ -63,11 +87,27 @@ public Account save(Account entity) { .set(ACCOUNTS.ROLE, entity.getRole()) .set(ACCOUNTS.EMAIL_VERIFIED, entity.isEmailVerified()) .set(ACCOUNTS.LOGIN_AUTH_MODES, normalizedLoginAuthModes(entity)) - .where(ACCOUNTS.ID.eq(entity.getId())) - .execute(); - if (updated != 1) { + .where(ACCOUNTS.ID.eq(entity.getId())); + if (expectedUuid != null) { + update = update.and(ACCOUNTS.ACCOUNT_UUID.eq(expectedUuid)); + } + if (expectedProvenance != null) { + update = update.and(ACCOUNTS.ACCOUNT_UUID_PROVENANCE.eq(expectedProvenance.name())); + } + if (expectedSourceNumericId != null) { + update = update.and(ACCOUNTS.ACCOUNT_UUID_SOURCE_NUMERIC_ID.eq(expectedSourceNumericId)); + } + AccountsRecord updated = update.returning().fetchOne(); + if (updated == null) { throw JooqAccountRepositorySupport.staleWrite("accounts", entity.getId()); } + requireExactIdentityReadback( + updated, + expectedUuid == null ? updated.getAccountUuid() : expectedUuid, + expectedProvenance == null + ? AccountIdentityProvenance.fromStorageValue(updated.getAccountUuidProvenance()) + : expectedProvenance); + copyIdentityToEntity(entity, updated); return entity; } @@ -78,15 +118,47 @@ public void delete(Account entity) { } private Account toEntity(AccountsRecord record) { - return JooqAccountRepositorySupport.partialAccount( - record.getId(), - record.getUsername(), - record.getEmail(), - record.getPasswordHash(), - record.getRole(), - record.getEmailVerified(), - record.getLoginAuthModes(), - record.getLifecycleState()); + Account account = + JooqAccountRepositorySupport.partialAccount( + record.getId(), + record.getUsername(), + record.getEmail(), + record.getPasswordHash(), + record.getRole(), + record.getEmailVerified(), + record.getLoginAuthModes(), + record.getLifecycleState()); + if (account != null) { + account.setAccountUuid(record.getAccountUuid()); + account.setAccountUuidProvenance( + AccountIdentityProvenance.fromStorageValue(record.getAccountUuidProvenance())); + account.setAccountUuidSourceNumericId(record.getAccountUuidSourceNumericId()); + requireExactIdentityReadback( + record, record.getAccountUuid(), account.getAccountUuidProvenance()); + } + return account; + } + + private void requireExactIdentityReadback( + AccountsRecord record, UUID expectedUuid, AccountIdentityProvenance expectedProvenance) { + if (record.getId() == null + || expectedUuid == null + || new UUID(0L, 0L).equals(expectedUuid) + || expectedProvenance == null + || !Objects.equals(record.getAccountUuid(), expectedUuid) + || !Objects.equals(record.getAccountUuidProvenance(), expectedProvenance.name()) + || !Objects.equals(record.getAccountUuidSourceNumericId(), record.getId())) { + throw new IllegalStateException( + "Account UUID readback did not match its exact persisted source row"); + } + } + + private void copyIdentityToEntity(Account entity, AccountsRecord record) { + entity.setId(record.getId()); + entity.setAccountUuid(record.getAccountUuid()); + entity.setAccountUuidProvenance( + AccountIdentityProvenance.fromStorageValue(record.getAccountUuidProvenance())); + entity.setAccountUuidSourceNumericId(record.getAccountUuidSourceNumericId()); } private String normalizedLoginAuthModes(Account entity) { diff --git a/services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql b/services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql new file mode 100644 index 0000000000..28323b9cfb --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql @@ -0,0 +1,87 @@ +-- Keep the numeric primary key as an Account-local storage detail while adding +-- the canonical, durable UUID identity required at cross-service boundaries. +-- Each retained UUID is assigned to its exact source row in place; the numeric +-- source is copied from that row's unchanged primary key. +ALTER TABLE accounts + ADD COLUMN account_uuid UUID, + ADD COLUMN account_uuid_provenance VARCHAR(40), + ADD COLUMN account_uuid_source_numeric_id BIGINT; + +UPDATE accounts +SET account_uuid = gen_random_uuid(), + account_uuid_provenance = 'ACCOUNT_V29_MIGRATION', + account_uuid_source_numeric_id = id; + +-- jOOQ's open-source DDL parser cannot model the PostgreSQL UUID generator default. +-- [jooq ignore start] +ALTER TABLE accounts ALTER COLUMN account_uuid SET DEFAULT gen_random_uuid(); +ALTER TABLE accounts + ALTER COLUMN account_uuid_provenance SET DEFAULT 'ACCOUNT_DATABASE_INSERT'; +-- [jooq ignore stop] + +ALTER TABLE accounts ALTER COLUMN account_uuid SET NOT NULL; +ALTER TABLE accounts ALTER COLUMN account_uuid_provenance SET NOT NULL; +ALTER TABLE accounts ALTER COLUMN account_uuid_source_numeric_id SET NOT NULL; +ALTER TABLE accounts + ADD CONSTRAINT accounts_account_uuid_unique UNIQUE (account_uuid); +ALTER TABLE accounts + ADD CONSTRAINT accounts_account_uuid_source_numeric_id_unique + UNIQUE (account_uuid_source_numeric_id); +ALTER TABLE accounts + ADD CONSTRAINT accounts_account_uuid_source_numeric_id_check + CHECK (account_uuid_source_numeric_id = id); +ALTER TABLE accounts + ADD CONSTRAINT accounts_account_uuid_non_nil_check + CHECK (account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID); +ALTER TABLE accounts + ADD CONSTRAINT accounts_account_uuid_provenance_check + CHECK (account_uuid_provenance IN ( + 'ACCOUNT_V29_MIGRATION', + 'ACCOUNT_REPOSITORY_INSERT', + 'ACCOUNT_DATABASE_INSERT' + )); + +-- The UUID and its source record are immutable identity evidence. The numeric +-- primary key remains unchanged and cannot be reassigned after UUID backfill. +-- [jooq ignore start] +CREATE FUNCTION account_identity_source_row_on_insert() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.account_uuid_provenance = 'ACCOUNT_V29_MIGRATION' THEN + RAISE EXCEPTION 'ACCOUNT_V29_MIGRATION provenance is reserved for retained rows' + USING ERRCODE = '23514', CONSTRAINT = 'accounts_identity_migration_insert_only'; + END IF; + NEW.account_uuid_source_numeric_id := NEW.id; + RETURN NEW; +END; +$$; + +CREATE TRIGGER accounts_identity_source_row_on_insert + BEFORE INSERT ON accounts + FOR EACH ROW + EXECUTE FUNCTION account_identity_source_row_on_insert(); + +CREATE FUNCTION account_identity_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.id IS DISTINCT FROM OLD.id + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.account_uuid_provenance IS DISTINCT FROM OLD.account_uuid_provenance + OR NEW.account_uuid_source_numeric_id IS DISTINCT FROM OLD.account_uuid_source_numeric_id THEN + RAISE EXCEPTION 'Account identity cannot be reassigned' + USING ERRCODE = '23514', CONSTRAINT = 'accounts_identity_immutable'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER accounts_identity_immutable + BEFORE UPDATE OF id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id + ON accounts + FOR EACH ROW + EXECUTE FUNCTION account_identity_immutable_guard(); +-- [jooq ignore stop] 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 132564086b..f8cf352cf7 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 @@ -5,6 +5,7 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.nio.file.Path; +import java.sql.SQLException; import java.time.Duration; import java.time.Instant; import java.time.LocalDateTime; @@ -22,6 +23,7 @@ import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; 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.AccountTenantMembership; import net.firedevops.firemud.accountservice.service.ExpiredConnectScopeCleanupJob; @@ -62,6 +64,7 @@ class AccountRepositoryIntegrationTest { "account_profile_identity_migration_proof"; private static final String GLOBAL_REGISTRATION_MIGRATION_PROOF_SCHEMA = "account_global_registration_migration_proof"; + private static final String ACCOUNT_UUID_MIGRATION_PROOF_SCHEMA = "account_uuid_migration_proof"; @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -751,6 +754,110 @@ void saveCanonicalizesEmail() { assertThat(repository.findByEmail(" PLAYER@EXAMPLE.COM ")).isPresent(); } + @Test + void repositoryPersistsAndReadsBackUniqueAccountUuidAndProvenance() { + Account saved = + repository.save( + account("uuid-account", "uuid-account@example.com", AccountLifecycleState.ACTIVE)); + UUID accountUuid = saved.getAccountUuid(); + + assertThat(accountUuid).isNotNull(); + assertThat(saved.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(saved.getAccountUuidSourceNumericId()).isEqualTo(saved.getId()); + + Account foundByNumericId = repository.findById(saved.getId()).orElseThrow(); + Account foundByUuid = repository.findByAccountUuid(accountUuid).orElseThrow(); + assertThat(foundByNumericId.getAccountUuid()).isEqualTo(accountUuid); + assertThat(foundByUuid.getId()).isEqualTo(saved.getId()); + assertThat(foundByUuid.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(foundByUuid.getAccountUuidSourceNumericId()).isEqualTo(saved.getId()); + + saved.setUsername("uuid-account-updated"); + Account updated = repository.save(saved); + assertThat(updated.getAccountUuid()).isEqualTo(accountUuid); + assertThat(updated.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(updated.getAccountUuidSourceNumericId()).isEqualTo(updated.getId()); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO accounts " + + "(username, email, password_hash, account_uuid, account_uuid_provenance) " + + "VALUES (?, ?, ?, ?, ?)", + "duplicate-uuid-account", + "duplicate-uuid-account@example.com", + "hash", + accountUuid, + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT.name())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("accounts_account_uuid_unique"); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO accounts " + + "(username, email, password_hash, account_uuid, account_uuid_provenance) " + + "VALUES (?, ?, ?, ?, ?)", + "nil-uuid-account", + "nil-uuid-account@example.com", + "hash", + new UUID(0L, 0L), + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT.name())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("accounts_account_uuid_non_nil_check"); + + var databaseInserted = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash) " + + "VALUES ('database-uuid-account', 'database-uuid@example.com', 'hash') " + + "RETURNING id, account_uuid, account_uuid_provenance, " + + "account_uuid_source_numeric_id")); + assertThat(databaseInserted.get("account_uuid", UUID.class)).isNotNull(); + assertThat(databaseInserted.get("account_uuid_provenance", String.class)) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT.name()); + assertThat(databaseInserted.get("account_uuid_source_numeric_id", Long.class)) + .isEqualTo(databaseInserted.get("id", Long.class)); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO accounts " + + "(username, email, password_hash, account_uuid, " + + "account_uuid_provenance) VALUES (?, ?, ?, ?, ?)", + "migration-origin-account", + "migration-origin@example.com", + "hash", + UUID.randomUUID(), + AccountIdentityProvenance.ACCOUNT_V29_MIGRATION.name())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("ACCOUNT_V29_MIGRATION provenance is reserved for retained rows") + .satisfies( + failure -> { + Throwable rootCause = failure; + while (rootCause.getCause() != null) { + rootCause = rootCause.getCause(); + } + assertThat(rootCause).isInstanceOf(SQLException.class); + assertThat(((SQLException) rootCause).getSQLState()).isEqualTo("23514"); + }); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM accounts WHERE username = 'migration-origin-account'", + Long.class)) + .isEqualTo(0L); + + saved.setAccountUuid(UUID.randomUUID()); + assertThatThrownBy(() -> repository.save(saved)) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("Failed to update accounts id="); + assertThat(repository.findById(saved.getId()).orElseThrow().getAccountUuid()) + .isEqualTo(accountUuid); + } + @ParameterizedTest @NullSource @ValueSource(strings = {"", " "}) @@ -1044,6 +1151,379 @@ void globalRegistrationMigrationPreservesAndQuarantinesUnprovenTenantRows() { .isEqualTo(0L); } + @Test + void accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity() { + String schema = ACCOUNT_UUID_MIGRATION_PROOF_SCHEMA; + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .target("28") + .load() + .migrate(); + + long firstAccountId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "INSERT INTO " + + schema + + ".accounts (username, email, password_hash, tenant_id) " + + "VALUES ('uuid-retained-one', 'uuid-retained-one@example.com', " + + "'hash-one', 41) RETURNING id")) + .longValue(); + long secondAccountId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "INSERT INTO " + + schema + + ".accounts (username, email, password_hash, tenant_id) " + + "VALUES ('uuid-retained-two', 'uuid-retained-two@example.com', " + + "'hash-two', 42) RETURNING id")) + .longValue(); + dsl.execute( + "INSERT INTO " + + schema + + ".profiles (account_id, tenant_id, display_name, bio) VALUES (?, ?, ?, ?)", + firstAccountId, + 41L, + "Retained profile", + "retained bio"); + dsl.execute( + "INSERT INTO " + + schema + + ".account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, FALSE, 'LEGACY_UNVERIFIED', 1, 1, 'LEGACY_UNVERIFIED')", + firstAccountId, + 41L); + dsl.execute( + "INSERT INTO " + + schema + + ".account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, 42, TRUE, 'ACTIVE', 2, 3, 'EXPLICIT_JOIN')", + secondAccountId); + UUID joinRealmId = REALM_ID; + String pendingJoinRequestId = "retained-v28-pending-join"; + String retainedConnectScopeId = "retained-scope-token"; + String worldSlug = "retained-world"; + String realmSlug = "retained-realm"; + String namespaceId = "retained-namespace"; + String playableStateScope = "REALM"; + long gameInstanceId = 7L; + long catalogRevision = 11L; + long pointerVersion = 13L; + String evaluatedAt = "2026-10-02T12:00:00Z"; + String connectScopeExpiresAt = "2099-10-02T12:00:00Z"; + VerifiedJoinScope retainedScopeBase = + new VerifiedJoinScope( + retainedConnectScopeId, + secondAccountId, + 42L, + joinRealmId, + worldSlug, + realmSlug, + namespaceId, + playableStateScope, + gameInstanceId, + catalogRevision, + pointerVersion, + evaluatedAt, + connectScopeExpiresAt, + "unused"); + String scopeDigest = AccountJoinDigest.scope(retainedScopeBase); + VerifiedJoinScope retainedScope = + new VerifiedJoinScope( + retainedScopeBase.connectScopeId(), + retainedScopeBase.accountId(), + retainedScopeBase.tenantId(), + retainedScopeBase.realmId(), + retainedScopeBase.worldSlug(), + retainedScopeBase.realmSlug(), + retainedScopeBase.playableStateNamespaceId(), + retainedScopeBase.playableStateScope(), + retainedScopeBase.gameInstanceId(), + retainedScopeBase.catalogRevision(), + retainedScopeBase.pointerVersion(), + retainedScopeBase.evaluatedAt(), + retainedScopeBase.connectScopeExpiresAt(), + scopeDigest); + String scopeTokenHash = AccountJoinDigest.tokenHash(retainedConnectScopeId); + dsl.execute( + "INSERT INTO " + + schema + + ".account_connect_scope_records " + + "(scope_token_hash, account_id, target_class, tenant_id, realm_id, world_slug, " + + "realm_slug, playable_state_namespace_id, playable_state_scope, game_instance_id, " + + "catalog_revision, pointer_version, evaluated_at, connect_scope_expires_at, " + + "snapshot_digest) " + + "VALUES (?, ?, 'PUBLIC_PRODUCTION', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + scopeTokenHash, + retainedScope.accountId(), + retainedScope.tenantId(), + retainedScope.realmId(), + retainedScope.worldSlug(), + retainedScope.realmSlug(), + retainedScope.playableStateNamespaceId(), + retainedScope.playableStateScope(), + retainedScope.gameInstanceId(), + retainedScope.catalogRevision(), + retainedScope.pointerVersion(), + retainedScope.evaluatedAt(), + retainedScope.connectScopeExpiresAt(), + retainedScope.snapshotDigest()); + String intentDigest = + AccountJoinDigest.intent(pendingJoinRequestId, retainedScope, "retained-caller"); + dsl.execute( + "INSERT INTO " + + schema + + ".account_join_operations " + + "(request_id, account_id, tenant_id, verified_caller_binding, scope_token_hash, " + + "connect_scope_digest, world_slug, realm_slug, realm_id, playable_state_namespace_id, " + + "playable_state_scope, game_instance_id, catalog_revision, pointer_version, " + + "intent_digest_version, intent_digest, caller_bound_authority_invalidated, status) " + + "VALUES (?, ?, ?, 'retained-caller', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, FALSE, " + + "'PENDING')", + pendingJoinRequestId, + retainedScope.accountId(), + retainedScope.tenantId(), + scopeTokenHash, + scopeDigest, + retainedScope.worldSlug(), + retainedScope.realmSlug(), + retainedScope.realmId(), + retainedScope.playableStateNamespaceId(), + retainedScope.playableStateScope(), + retainedScope.gameInstanceId(), + retainedScope.catalogRevision(), + retainedScope.pointerVersion(), + intentDigest); + + UUID auditEventId = UUID.fromString("1596dcce-a52c-4c39-86bf-138a06069012"); + String payload = "{\"accountId\":" + firstAccountId + ",\"event\":\"retained\"}"; + String payloadDigest = AccountAuditDigest.ofPayload(payload); + dsl.execute( + "INSERT INTO " + + schema + + ".account_audit_outbox " + + "(audit_event_id, scope, producer_service, event_type, occurred_at, schema_version, " + + "payload_digest_version, payload_digest, payload) " + + "VALUES (?, 'platform', 'account-service', 'ACCOUNT_REGISTERED', " + + "TIMESTAMP '2026-09-01 12:00:00', 1, 1, ?, ?)", + auditEventId, + payloadDigest, + payload); + + String firstAccountBefore = + jsonRow( + "SELECT to_jsonb(a)::text FROM " + schema + ".accounts a WHERE id = ?", firstAccountId); + String secondAccountBefore = + jsonRow( + "SELECT to_jsonb(a)::text FROM " + schema + ".accounts a WHERE id = ?", + secondAccountId); + String profileBefore = + jsonRow( + "SELECT to_jsonb(p)::text FROM " + schema + ".profiles p WHERE account_id = ?", + firstAccountId); + String membershipBefore = + jsonRow( + "SELECT to_jsonb(m)::text FROM " + + schema + + ".account_tenant_membership m WHERE account_id = ?", + firstAccountId); + String explicitMembershipBefore = + jsonRow( + "SELECT to_jsonb(m)::text FROM " + + schema + + ".account_tenant_membership m WHERE account_id = ?", + secondAccountId); + String pendingJoinBefore = + jsonRow( + "SELECT to_jsonb(j)::text FROM " + + schema + + ".account_join_operations j WHERE request_id = ?", + pendingJoinRequestId); + String retainedConnectScopeBefore = + jsonRow( + "SELECT to_jsonb(s)::text FROM " + + schema + + ".account_connect_scope_records s WHERE scope_token_hash = ?", + scopeTokenHash); + String outboxBefore = + jsonRow( + "SELECT to_jsonb(o)::text FROM " + + schema + + ".account_audit_outbox o WHERE audit_event_id = ?", + auditEventId); + + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .load() + .migrate(); + + String accountProjection = + "(to_jsonb(a) - 'account_uuid' - 'account_uuid_provenance' " + + "- 'account_uuid_source_numeric_id')::text"; + assertThat( + jsonRow( + "SELECT " + accountProjection + " FROM " + schema + ".accounts a WHERE id = ?", + firstAccountId)) + .isEqualTo(firstAccountBefore); + assertThat( + jsonRow( + "SELECT " + accountProjection + " FROM " + schema + ".accounts a WHERE id = ?", + secondAccountId)) + .isEqualTo(secondAccountBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(p)::text FROM " + schema + ".profiles p WHERE account_id = ?", + firstAccountId)) + .isEqualTo(profileBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(m)::text FROM " + + schema + + ".account_tenant_membership m WHERE account_id = ?", + firstAccountId)) + .isEqualTo(membershipBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(m)::text FROM " + + schema + + ".account_tenant_membership m WHERE account_id = ?", + secondAccountId)) + .isEqualTo(explicitMembershipBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(j)::text FROM " + + schema + + ".account_join_operations j WHERE request_id = ?", + pendingJoinRequestId)) + .isEqualTo(pendingJoinBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(s)::text FROM " + + schema + + ".account_connect_scope_records s WHERE scope_token_hash = ?", + scopeTokenHash)) + .isEqualTo(retainedConnectScopeBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(o)::text FROM " + + schema + + ".account_audit_outbox o WHERE audit_event_id = ?", + auditEventId)) + .isEqualTo(outboxBefore); + + UUID firstUuid = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT account_uuid FROM " + schema + ".accounts WHERE id = ?", firstAccountId) + .fetchOne(0, UUID.class)); + UUID secondUuid = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT account_uuid FROM " + schema + ".accounts WHERE id = ?", + secondAccountId) + .fetchOne(0, UUID.class)); + assertThat(firstUuid).isNotEqualTo(secondUuid); + assertThat(firstUuid).isNotEqualTo(new UUID(0L, 0L)); + assertThat(secondUuid).isNotEqualTo(new UUID(0L, 0L)); + assertThat( + dsl.resultQuery( + "SELECT account_uuid_provenance FROM " + schema + ".accounts WHERE id = ?", + firstAccountId) + .fetchOne(0, String.class)) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_V29_MIGRATION.name()); + assertThat( + dsl.resultQuery( + "SELECT account_uuid_source_numeric_id FROM " + + schema + + ".accounts WHERE id = ?", + firstAccountId) + .fetchOne(0, Long.class)) + .isEqualTo(firstAccountId); + assertThat( + dsl.resultQuery("SELECT COUNT(DISTINCT account_uuid) FROM " + schema + ".accounts") + .fetchOne(0, Long.class)) + .isEqualTo(2L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM " + + schema + + ".account_audit_outbox WHERE payload_digest = ?", + payloadDigest) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE " + schema + ".accounts SET account_uuid = ? WHERE id = ?", + UUID.randomUUID(), + firstAccountId)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Account identity cannot be reassigned") + .satisfies( + failure -> { + Throwable rootCause = failure; + while (rootCause.getCause() != null) { + rootCause = rootCause.getCause(); + } + assertThat(rootCause).isInstanceOf(SQLException.class); + assertThat(((SQLException) rootCause).getSQLState()).isEqualTo("23514"); + }); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE " + schema + ".accounts SET account_uuid_provenance = ? WHERE id = ?", + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT.name(), + firstAccountId)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Account identity cannot be reassigned") + .satisfies( + failure -> { + Throwable rootCause = failure; + while (rootCause.getCause() != null) { + rootCause = rootCause.getCause(); + } + assertThat(rootCause).isInstanceOf(SQLException.class); + assertThat(((SQLException) rootCause).getSQLState()).isEqualTo("23514"); + }); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE " + + schema + + ".accounts SET account_uuid_source_numeric_id = ? WHERE id = ?", + firstAccountId + 10, + firstAccountId)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Account identity cannot be reassigned") + .satisfies( + failure -> { + Throwable rootCause = failure; + while (rootCause.getCause() != null) { + rootCause = rootCause.getCause(); + } + assertThat(rootCause).isInstanceOf(SQLException.class); + assertThat(((SQLException) rootCause).getSQLState()).isEqualTo("23514"); + }); + assertThat( + dsl.resultQuery( + "SELECT account_uuid FROM " + schema + ".accounts WHERE id = ?", firstAccountId) + .fetchOne(0, UUID.class)) + .isEqualTo(firstUuid); + } + private Account account(String username, String email, AccountLifecycleState lifecycleState) { Account account = new Account(); account.setUsername(username); @@ -1054,4 +1534,8 @@ private Account account(String username, String email, AccountLifecycleState lif account.setLifecycleState(lifecycleState); return account; } + + private String jsonRow(String query, Object... bindings) { + return Objects.requireNonNull(dsl.fetchOne(query, bindings)).get(0, String.class); + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayCommand.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayCommand.java index 149faeb53d..2657519a9c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayCommand.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayCommand.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.entity; import java.time.Instant; +import java.util.UUID; import lombok.Data; @Data @@ -10,7 +11,10 @@ public class GameplayCommand { private Long tenantId; private Long gameInstanceId; private Long sessionId; + // Retained private numeric evidence; never derive a logical Account identity from this value. private Long accountId; + // Canonical Account identity supplied by a verified producer, not a numeric-key migration. + private UUID accountUuid; private Long characterId; private String commandName; private String commandText; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java index 4d7dd7ddb5..7b1e6fc3df 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java @@ -603,6 +603,7 @@ private void populate(GameplayCommandRecord record, GameplayCommand entity) { record.setGameInstanceId(entity.getGameInstanceId()); record.setSessionId(entity.getSessionId()); record.setAccountId(entity.getAccountId()); + record.setAccountUuid(entity.getAccountUuid()); record.setCharacterId(entity.getCharacterId()); record.setCommandName(entity.getCommandName()); record.setCommandText(entity.getCommandText()); @@ -661,6 +662,7 @@ private GameplayCommand toEntity(Record record) { entity.setGameInstanceId(record.get(GAMEPLAY_COMMAND.GAME_INSTANCE_ID)); entity.setSessionId(record.get(GAMEPLAY_COMMAND.SESSION_ID)); entity.setAccountId(record.get(GAMEPLAY_COMMAND.ACCOUNT_ID)); + entity.setAccountUuid(record.get(GAMEPLAY_COMMAND.ACCOUNT_UUID)); entity.setCharacterId(record.get(GAMEPLAY_COMMAND.CHARACTER_ID)); entity.setCommandName(record.get(GAMEPLAY_COMMAND.COMMAND_NAME)); entity.setCommandText(record.get(GAMEPLAY_COMMAND.COMMAND_TEXT)); diff --git a/services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql b/services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql new file mode 100644 index 0000000000..b551ae0076 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql @@ -0,0 +1,11 @@ +-- Retained numeric Account IDs remain untouched; historical commands receive no +-- inferred UUID because Game Session does not own the Account identity mapping. +ALTER TABLE gameplay_command + ADD COLUMN account_uuid UUID; + +ALTER TABLE gameplay_command + ADD CONSTRAINT chk_gameplay_command_account_uuid_non_nil + CHECK ( + account_uuid IS NULL + OR account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + ); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java new file mode 100644 index 0000000000..40a179afb7 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java @@ -0,0 +1,91 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; + +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Testcontainers; + +@SuppressWarnings("resource") +@Testcontainers(disabledWithoutDocker = true) +class GameplayCommandAccountUuidMigrationIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Test + void migrationRetainsLegacyCommandRowsAndDoesNotInventAccountUuids() { + try (PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine")) { + postgres.start(); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("10")) + .load() + .migrate(); + + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + insertLegacyCommand(dsl, "legacy-account-101", 101L); + insertLegacyCommand(dsl, "legacy-account-202", 202L); + insertLegacyCommand(dsl, "legacy-account-null", null); + List beforeMigrationRows = + dsl.fetch( + "SELECT to_jsonb(command_row)::text AS retained_row " + + "FROM gameplay_command AS command_row ORDER BY command_id") + .getValues("retained_row", String.class); + + Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + + List migratedRows = + dsl.fetch( + "SELECT command_id, account_id, account_uuid " + + "FROM gameplay_command ORDER BY command_id"); + assertThat(migratedRows) + .extracting( + row -> row.get("command_id", String.class), + row -> row.get("account_id", Long.class), + row -> row.get("account_uuid", UUID.class)) + .containsExactly( + tuple("legacy-account-101", 101L, null), + tuple("legacy-account-202", 202L, null), + tuple("legacy-account-null", null, null)); + List migratedLegacyRows = + dsl.fetch( + "SELECT (to_jsonb(command_row) - 'account_uuid')::text AS retained_row " + + "FROM gameplay_command AS command_row ORDER BY command_id") + .getValues("retained_row", String.class); + assertThat(migratedLegacyRows).containsExactlyElementsOf(beforeMigrationRows); + } + } + + private static void insertLegacyCommand(DSLContext dsl, String commandId, Long accountId) { + dsl.execute( + "INSERT INTO gameplay_command (command_id, tenant_id, game_instance_id, session_id, " + + "account_id, command_name, sanitized_command_text, requires_solo_tick, " + + "execution_outcome, gameplay_result, accepted_at, staged_at, completed_at, " + + "last_attempt_at, attempt_count, source_type, command_text, " + + "playable_state_scope, world_slug, realm_slug) " + + "VALUES (?, 1, 7, 11, ?, 'look', 'look', false, 'APPLIED', 'SUCCESS', " + + "TIMESTAMP '2000-01-01 12:00:00', TIMESTAMP '2000-01-01 12:00:10', " + + "TIMESTAMP '2000-01-01 12:01:00', TIMESTAMP '2000-01-01 12:01:00', 1, " + + "'PLAYER', 'look', '', '', '')", + commandId, + accountId); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java index 711925e605..a575499a9b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java @@ -12,6 +12,7 @@ import java.time.Instant; import java.time.LocalDateTime; import java.util.List; +import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -511,6 +512,117 @@ void commandIdMayBeReusedAcrossScopesButConflictsWithinOneScope() { .hasMessageContaining("idx_gameplay_command_tenant_instance_command_id"); } + @Test + void saveRoundTripsExplicitAccountUuidWithoutChangingLegacyNumericAccountId() { + UUID accountUuid = UUID.fromString("a190bcb9-8680-4acd-b86f-3cae3fe1635f"); + GameplayCommand command = repositoryCommand("account-uuid-command", "PLAYER"); + command.setAccountId(712L); + command.setAccountUuid(accountUuid); + + GameplayCommand saved = repository.save(command); + + assertThat(saved) + .extracting(GameplayCommand::getAccountId, GameplayCommand::getAccountUuid) + .containsExactly(712L, accountUuid); + assertThat( + repository.findByTenantIdAndGameInstanceIdAndCommandId(1L, 7L, "account-uuid-command")) + .get() + .extracting(GameplayCommand::getAccountId, GameplayCommand::getAccountUuid) + .containsExactly(712L, accountUuid); + + saved.setAccountUuid(null); + saved.setAttemptCount(1); + GameplayCommand updated = repository.save(saved); + + assertThat(updated) + .extracting(GameplayCommand::getAccountId, GameplayCommand::getAccountUuid) + .containsExactly(712L, accountUuid); + assertThat(updated.getAttemptCount()).isEqualTo(1); + + UUID attemptedReplacement = UUID.fromString("3317ade3-c0e6-437a-ae8d-af77d1ec497d"); + updated.setAccountUuid(attemptedReplacement); + updated.setAttemptCount(2); + GameplayCommand replacementAttempt = repository.save(updated); + + assertThat(replacementAttempt) + .extracting(GameplayCommand::getAccountId, GameplayCommand::getAccountUuid) + .containsExactly(712L, accountUuid); + assertThat(replacementAttempt.getAttemptCount()).isEqualTo(2); + assertThat( + repository.findByTenantIdAndGameInstanceIdAndCommandId(1L, 7L, "account-uuid-command")) + .get() + .extracting(GameplayCommand::getAccountId, GameplayCommand::getAccountUuid) + .containsExactly(712L, accountUuid); + } + + @Test + void saveRoundTripsNullableAccountUuidAlongsideLegacyNumericAccountId() { + GameplayCommand command = repositoryCommand("legacy-account-command", "PLAYER"); + command.setAccountId(908L); + command.setAccountUuid(null); + + GameplayCommand saved = repository.save(command); + + assertThat(saved) + .extracting(GameplayCommand::getAccountId, GameplayCommand::getAccountUuid) + .containsExactly(908L, null); + assertThat( + repository.findByTenantIdAndGameInstanceIdAndCommandId( + 1L, 7L, "legacy-account-command")) + .get() + .extracting(GameplayCommand::getAccountId, GameplayCommand::getAccountUuid) + .containsExactly(908L, null); + + saved.setAccountUuid(UUID.fromString("4317ade3-c0e6-437a-ae8d-af77d1ec497d")); + GameplayCommand updated = repository.save(saved); + + assertThat(updated) + .extracting(GameplayCommand::getAccountId, GameplayCommand::getAccountUuid) + .containsExactly(908L, null); + assertThat( + repository.findByTenantIdAndGameInstanceIdAndCommandId( + 1L, 7L, "legacy-account-command")) + .get() + .extracting(GameplayCommand::getAccountId, GameplayCommand::getAccountUuid) + .containsExactly(908L, null); + } + + @Test + void saveRejectsNilAccountUuidAtDatabaseFence() { + GameplayCommand command = repositoryCommand("nil-account-uuid-command", "PLAYER"); + command.setAccountId(101L); + command.setAccountUuid(new UUID(0L, 0L)); + + assertThatThrownBy(() -> repository.save(command)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("chk_gameplay_command_account_uuid_non_nil"); + assertThat(dsl.fetchCount(GAMEPLAY_COMMAND)).isZero(); + } + + @Test + void accountUuidEvidenceInsertRollsBackWithItsContainingTransaction() { + UUID accountUuid = UUID.fromString("5317ade3-c0e6-437a-ae8d-af77d1ec497d"); + GameplayCommand command = repositoryCommand("rolled-back-account-uuid-command", "PLAYER"); + command.setAccountId(345L); + command.setAccountUuid(accountUuid); + + assertThatThrownBy( + () -> + transactionTemplate.executeWithoutResult( + status -> { + repository.save(command); + throw new IllegalStateException("force transaction rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("force transaction rollback"); + + assertThat( + repository.findByTenantIdAndGameInstanceIdAndCommandId( + 1L, 7L, "rolled-back-account-uuid-command")) + .isEmpty(); + assertThat(dsl.fetchCount(GAMEPLAY_COMMAND)).isZero(); + } + @Test void updatePreservesAdmittedAuthoredActionSnapshot() { GameplayCommand command = new GameplayCommand();