From 610ea7b7bcf9f959dbffd452848c710b56e9411b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 21:57:54 +1300 Subject: [PATCH 01/23] Commit Account-owned LEFT authority with immutable retry and inactive proof --- .github/workflows/ci.yml | 7 + .../account-service/runtime-and-data.md | 4 +- .../player-access-and-session.md | 14 +- .../MembershipTransitionReceiptDigest.java | 11 +- .../dto/RuntimeMembershipSnapshotDto.java | 11 +- .../AccountAuditOutboxRepository.java | 22 + ...MembershipTransitionReceiptRepository.java | 188 ++++- ...countMembershipAuthorityEventProducer.java | 309 +++++++- .../AccountMembershipLifecycleService.java | 426 +++++++++++ .../service/impl/AccountGrpcService.java | 8 +- ...nt_membership_left_transition_receipts.sql | 28 + .../AccountJoinPostgresIntegrationTest.java | 720 +++++++++++++++++- ...MembershipTransitionReceiptDigestTest.java | 86 +++ ...ershipTransitionReceiptRepositoryTest.java | 90 +++ ...tMembershipAuthorityEventProducerTest.java | 60 ++ ...AccountMembershipLifecycleServiceTest.java | 197 +++++ .../service/impl/AccountGrpcServiceTest.java | 224 +++++- .../command/text/PlayCommandHandlerTest.java | 241 +++++- .../RuntimeMembershipTestFixtures.java | 73 +- 19 files changed, 2633 insertions(+), 86 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipLifecycleService.java create mode 100644 services/account-service/src/main/resources/db/migration/V40__account_membership_left_transition_receipts.sql create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipLifecycleServiceTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e9667d8ed5..0c25bb4393 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -975,6 +975,13 @@ jobs: --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#positiveMembershipSnapshotRejectsScalarAndWrongTenantVersionMaps()' \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#concurrentFirstJoinCannotMixWithCompleteFencedRuntimeMembershipSnapshot()' \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#canonicalExistingPairBoundPositiveMembershipSnapshotRepeatsWithoutMutation()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#leftCommitsClosedAuthorityAndRetainedInactiveRuntimeSnapshot()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#concurrentExactLeftRetriesAndReplayAfterReactivationDoNotChurnCurrentAuthority()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#committedLeftWithLostAcknowledgementReadsBackExactReceiptWithoutChurn()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#reusedLeftAndJoinRequestIdsAreRejectedWithoutCrossScopeMutation()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#contradictoryLatestEventDeniesLeftWithoutMembershipOrOutboxMutation()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#auditFailureRollsBackCompleteOwnerLeftTransaction()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#concurrentLeftAndReactivationSerializeAsCompleteAccountTransitions()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest#claimOnlyTransactionRollsBackPendingExchange()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#concurrentExactIssuanceClaimsHaveOneTerminalFirstWriter()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#lostIssuanceResponseRecoversExactEncryptedResultFromDurableReadback(Path)' \ diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 9d09e1c892..749c0718ef 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -16,7 +16,7 @@ Account V25 enforces the live tenant-scoped profile identity `(tenantId, account Account V29 keeps the numeric `accounts.id` primary key and adds an immutable canonical `account_uuid` per Account. Retained rows receive `ACCOUNT_V29_MIGRATION` provenance and a source numeric row equal to their unchanged primary key; an Account insert trigger binds new rows to their numeric key, while `AccountRepository` assigns UUIDs with `ACCOUNT_REPOSITORY_INSERT` provenance and verifies exact persisted identity readback. Database uniqueness constraints prevent duplicate UUID/source mappings. This is an Account persistence bridge only: REST/gRPC DTOs, JWT identities, and external callers remain numeric, and this migration does not create or infer tenant UUID mappings. The focused repository/migration integration class compiled successfully, but all 13 cases were skipped because Docker was unavailable; V29 PostgreSQL migration and immutability behavior therefore remains unexecuted runtime proof. -The current Unit 1B draft adds V31 positive authority-generation rows and an account-local issuance fence, enrolls the exact JWT issuer idempotently at startup, initializes new global Account UUID generation and fence in the registration transaction, and enrolls a canonical tenant generation only after approved retained-row association readback. V34 enrolls retained Account UUIDs into both Account generation and fence state without resetting an advanced pair; a half-pair aborts. V33 provides independently sequenced immutable authority events, and the shared closed membership-event codec has Account/Game Session canonicalization vectors. The local V36 candidate adds an Account-owned durable authority row for each verified Account/tenant pair: a never-joined pair has positive version and generation at sequence zero before JOIN, while the first JOIN advances version to two and event sequence to one without independently advancing generation. Its sequence-zero read requires pair provenance, row/receipt/event absence, and the complete tuple under one Account fence; it never grants admission. Retained positive rows can enroll only from exact current event and receipt evidence without renumbering, while contradictory and inactive retained rows remain denied. The current explicit JOIN candidate composes the approved retained tenant UUID, membership generation and fence, role snapshot, canonical V33 event, receipt, audit, and terminal operation in its Account transaction; exact replay and abandoned-`PENDING` recovery require event readback. Retained inactive reactivation still denies without a canonical current INACTIVE event, and the runtime RPC, event delivery/Redis projection, Game Session consumer, and fresh-tenant UUID handoff remain open. Neither V31/V36 enrollment nor this JOIN-local event fences an old issuer binary or completes token issuance. V35 is an unwired Account-owned connect-issuance operation/envelope storage candidate; production issuance still uses the legacy path, and key-ring deployment and exact-result recovery proof remain open. Detailed current proof and rollout limits remain in the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md). +The current Unit 1B draft adds V31 positive authority-generation rows and an account-local issuance fence, enrolls the exact JWT issuer idempotently at startup, initializes new global Account UUID generation and fence in the registration transaction, and enrolls a canonical tenant generation only after approved retained-row association readback. V34 enrolls retained Account UUIDs into both Account generation and fence state without resetting an advanced pair; a half-pair aborts. V33 provides independently sequenced immutable authority events, and the shared closed membership-event codec has Account/Game Session canonicalization vectors. The local V36 candidate adds an Account-owned durable authority row for each verified Account/tenant pair: a never-joined pair has positive version and generation at sequence zero before JOIN, while the first JOIN advances version to two and event sequence to one without independently advancing generation. Its sequence-zero read requires pair provenance, row/receipt/event absence, and the complete tuple under one Account fence; it never grants admission. Retained positive rows can enroll only from exact current event and receipt evidence without renumbering, while contradictory or unproved inactive retained rows remain denied. The current explicit JOIN candidate composes the approved retained tenant UUID, membership generation and fence, role snapshot, canonical V33 event, receipt, audit, and terminal operation in its Account transaction; exact replay and abandoned-`PENDING` recovery require event readback. An unwired Account-owned LEFT component now transitions only an already-proved retained ACTIVE pair to retained INACTIVE state; its exact current-INACTIVE reader requires the existing pair plus matching latest positive LEFT receipt and canonical event, and it does not turn historical replay into current authority after reactivation. This component does not expose a route or caller authentication and has no executed PostgreSQL proof yet. Account runtime RPC enablement, event delivery/Redis projection, Game Session consumer, and fresh-tenant UUID handoff remain open. Neither V31/V36 enrollment nor the JOIN/LEFT-local event fences an old issuer binary or completes token issuance. V35 is an unwired Account-owned connect-issuance operation/envelope storage candidate; production issuance still uses the legacy path, and key-ring deployment and exact-result recovery proof remain open. Detailed current proof and rollout limits remain in the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md). The fresh-tenant Account consumer is a UUID-only owner boundary, separate from retained-manifest import and membership authority. The Account normal workload authenticates to Game Design's `ResolveFreshTenantCreation` read, verifies the closed operation-bound request, digest, source, and receipt evidence, then stores an immutable canonical-UUID association under a claim index shared with retained associations; that index rejects conflicts regardless of which evidence path arrives first. Unknown response fields fail closed rather than extending this evidence implicitly. Only after exact source readback may Account commit the association and invoke existing tenant-generation initialization without resetting existing state. Both the fresh-source client and the distinct retained-association client require file-backed workload mTLS and the configured workload namespace; before accepting response content they verify the exact Game Design server workload URI under the [cross-service trust owner](../../system-architecture-security.md#cross-service-trust), not merely a trusted CA or DNS name. Missing, ambiguous, another-service or cross-namespace server identity denies the read. The #2915 source and association components now have passing focused PostgreSQL proof, with the limits recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md); mocked client and local TLS construction are not live authenticated handoff or activation proof. They create no numeric Account tenant alias or selector and enable no runtime path. The identity direction is owned by [Multi-Tenancy](../../system-architecture-multi-tenancy.md#canonical-identity-and-retained-key-bridge), and Game Design's evidence contract by its [API contract](../game-design-service/api-contracts.md#fresh-tenant-creation-operation-and-account-readback). @@ -24,7 +24,7 @@ The V39 candidate extends the existing pair authority table for that UUID-only a Account implements bounded owner-local cleanup of expired password-reset, email-verification, and email-login-challenge SQL rows, with per-family deleted-row counts and oldest-expired-row lag metrics. The cleanup uses the same process-local wall-clock basis as current credential issuance and validation against timezone-less SQL timestamps; cross-node timezone normalization and existing-row migration are not established by this cleanup. Focused unit proof in `ExpiredCredentialCleanupJobTest` has executed locally; PostgreSQL repository integration cases in `CredentialCleanupRepositoryIntegrationTest` compile but were skipped because Docker was unavailable. This cleanup does not claim atomic token consumption, session revocation, or completion of the full [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) retention contract; shared retention classes, dependency horizons, blockers, holds, and cross-service proof remain outstanding. -The current public registration path creates only a global Account row and a platform-scoped audit outbox record; a caller-supplied legacy `tenantId` creates no membership authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. Its policy-independent `PENDING` intent binds the verified caller, retained connect scope, and request digest; after authoritative entitlement evaluation, a separate Account transaction binds `allowPublicJoin` and `entitlementVersion`, revalidates both at the commit gate, and commits any first membership transition with role snapshot, V31 generation/fence, V33 authority event, provisional receipt, tenant audit, and terminal operation outcome. Entitlement unavailability keeps policy values unset and the operation pending; expiry or an absent row cannot prove a terminal outcome. Exact replay checks the stored digest and, for committed JOIN, the immutable request event; active-membership success and abandoned-`PENDING` reconciliation require current event, role, receipt, membership, and authority-tuple readback. Contradictory or unavailable evidence fails closed or remains pending, with bounded reconciliation attempts. Retained inactive reactivation is unavailable until an exact current INACTIVE authority event and writer exist; a manually changed membership row is not proof. Focused local unit tests execute, but PostgreSQL lost-acknowledgement, competing-request concurrency, and direct text-to-Logging proof are not established by local skipped integration cases. Retained legacy memberships remain unverified and non-admitting; affected deployment still requires verified no-data or explicit retained-row disposition/mapping and admission-isolation readback. See the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md) for detailed evidence and remaining gates. +The current public registration path creates only a global Account row and a platform-scoped audit outbox record; a caller-supplied legacy `tenantId` creates no membership authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. Its policy-independent `PENDING` intent binds the verified caller, retained connect scope, and request digest; after authoritative entitlement evaluation, a separate Account transaction binds `allowPublicJoin` and `entitlementVersion`, revalidates both at the commit gate, and commits any first membership transition with role snapshot, V31 generation/fence, V33 authority event, provisional receipt, tenant audit, and terminal operation outcome. Entitlement unavailability keeps policy values unset and the operation pending; expiry or an absent row cannot prove a terminal outcome. Exact replay checks the stored digest and, for committed JOIN, the immutable request event; active-membership success and abandoned-`PENDING` reconciliation require current event, role, receipt, membership, and authority-tuple readback. Contradictory or unavailable evidence fails closed or remains pending, with bounded reconciliation attempts. A separate unwired AccountMembershipLifecycleService candidate commits LEFT only from exact current positive ACTIVE membership evidence, retains the membership and role snapshot, advances membership version and authority generation, and appends the canonical invalidating event, transition receipt, audit envelope, and pair authority in its owner transaction. Exact retry reads back that original receipt/event/audit result; after reactivation it does not return that historical result as current authority. The held-back INACTIVE snapshot reader rejects sequence-zero baselines and requires the existing pair, current membership/roles, latest positive LEFT receipt, current checkpoint/event, and matching generation/fence. The LEFT component has no executed PostgreSQL proof yet and does not add public route authentication or enable the runtime RPC. Executed JOIN proof and the new LEFT component's local PostgreSQL skips are distinguished in the owning tracker; neither establishes direct text-to-Logging delivery or complete end-to-end admission. Retained legacy memberships remain unverified and non-admitting; affected deployment still requires verified no-data or explicit retained-row disposition/mapping and admission-isolation readback. See the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md) for detailed evidence and remaining gates. Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. 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 02456d463b..d4c3a4744f 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,14 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The owner-local LEFT candidate passed the consolidated Account/Game Session full checks, affected Java formatting, both service JARs, Checkstyle, SpotBugs, JaCoCo, links, Markdown and Flyway sanity (12 sets/124 files): 153 tasks, 21 executed/132 up-to-date. Account's 469 unit cases and Game Session's 1,731 unit cases executed successfully in the preceding same-code gates; unchanged unit tasks were up-to-date in the final gate. Game Session also executed 18 non-PostgreSQL integration cases and one cross-service case; 17 unit, 116 integration and 33 cross-service cases skipped. All 145 Account PostgreSQL cases, including the expanded 38-case JOIN/LEFT suite and seven required LEFT methods, compiled/discovered but skipped without Docker. Actionlint, all 23 CI-scope contracts and diff hygiene passed. Mocked INACTIVE consumer negatives preserve the production lifecycle guard and distinguish unbound denial from cleanup of an existing binding. Exact-candidate PostgreSQL execution, fresh-image startup and authenticated end-to-end producer/consumer proof remain required; no runtime path is enabled. + +Exact parent `642d5d9f58d8e383c8614697f88f085ef3f56b39` [CI36835527324](https://github.com/benhook1013/FireMUD/actions/runs/36835527324) passed the strict five-case Game Session authored-world intake proof with zero skips/failures/errors. Account strict JOIN31, exchange9, issuance9, source/history18, association6, pair8, fresh UUID snapshot11 and generation2/outbox4, plus Game Design creation8/authored-source10, also passed without skips/failures/errors. These are runner-JUnit verifier results, not uploaded raw XML. Aggregate CI failed, with Game Session's broader check cancelled after 18 CommunicationWebSocket failures; Script Pin25 and focused WebSocket16 proof are not credited. This parent execution does not prove the new LEFT candidate or enable catalog, membership or credential paths. + +2026-10-01 Account has an unwired owner-local LEFT component candidate in `AccountMembershipLifecycleService` with V40 receipt-state support. It accepts only an already-proved retained ACTIVE membership pair and, in one Account owner transaction, marks the retained row INACTIVE/non-admitting, preserves its role set, advances membership version and authority generation, and records the canonical invalidating authority event, provisional transition receipt, audit envelope, and pair authority. Exact replay verifies the original immutable event/receipt/audit result; after reactivation it remains historical readback, not current authority. The held-back current-INACTIVE reader requires the existing pair, membership and roles plus the exact latest positive LEFT receipt and matching current checkpoint/event/fence; it does not accept sequence zero, enroll a missing pair, or authorize admission. Public caller authentication/route, fresh-UUID positive JOIN and lifecycle, advanced upstream authority, delivery/projection and consumer convergence, runtime RPC enablement, and credential/catalog activation remain open. PostgreSQL cases for LEFT, replay after reactivation, lost acknowledgement, concurrency, contradiction and rollback are present but have not executed on this candidate; local Docker is unavailable, so no PostgreSQL pass is claimed. [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md), [Authentication](../../architecture/system-architecture-authentication.md), [ADR 0030](../../architecture/decisions/adr-0030-risk-based-active-session-revocation.md), and [ADR 0036](../../architecture/decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md) remain the owners of public lifecycle behavior and authority-generation/revocation semantics. + +Bounded diagnosis of exact prior-head [CI 36826897436](https://github.com/benhook1013/FireMUD/actions/runs/36826897436) on `ada803afcf69fd69555f5ecad55275e424d8623e`: the new CommunicationWebSocket cases need `OK PLAY` or, where public membership is missing, `JOIN_REQUIRED` to reach their communication assertions, but the production path fails before those assertions. The run logs lack response text; the static carrier trace shows `LOGIN` retains numeric Account ID, `PLAY` builds a numeric Account/tenant `PlayerExecutionContext`, and production `AccountClient` requires canonical non-nil UUIDs and denies before the Account stub, which `PLAY` reports as `AUTH_UNAVAILABLE`. The test stub's numeric UUID formatter is not production identity authority, and its numeric request echoes conflict with the UUID protocol. This is an open identity-carrier prerequisite and failed proof, not evidence of an inherited/flaky failure or a resolved path: genuine Account identity, Game Design/Game Session tenant association, and UUID carriers are still required. + Exact `ab93efc392fb57e53b7126d0d9ee639dce0bcd23` [CI36833651399](https://github.com/benhook1013/FireMUD/actions/runs/36833651399) resolved cross-service Flyway discovery and executed all five Game Session intake PostgreSQL cases: four passed, one failed, none skipped. The remaining failure is the tenant-binding truncate assertion: PostgreSQL rejects the referencing foreign key before reaching the expected immutable trigger. The focused correction keeps that foreign-key rejection proof and separately exercises the immutable trigger with the dependent tables included; exact corrected execution remains required. Uploaded Game Session reports are HTML-only and the strict verifier did not run, so this is execution/failure evidence, not strict success. Account again passed strict JOIN31, exchange9, issuance9, source/history18, fresh association6, pair8, fresh UUID snapshot11 and generation2/outbox4 with zero skips/failures/errors. Game Design creation8/authored-source10 passed strict; its broader retained fixture and other aggregate failures remain open. Later Game Session check, Script Pin25 and WebSocket16 gates skipped after the early intake failure. No runtime activation or corpus completion is claimed. Exact `03753754573afbcd5742354b4bb73cc4e8d4d2c8` [CI36831541847](https://github.com/benhook1013/FireMUD/actions/runs/36831541847) executed and passed strict Account JOIN31, bare-LOGIN storage9, connect issuance9, committed source/history18, fresh association6, pair8, fresh UUID snapshot11 and generation2/outbox4, all zero skips/failures/errors. The corrected repeated-positive read and its complete no-mutation assertion executed once and passed. Game Design creation8/authored-source10 also passed strict; the wider separately routed retained fixture remains red. The mandatory early Game Session intake task reached all five PostgreSQL cases, but all failed before repository behavior because the new fixture's classpath migration scan included other services' V1 migrations. HTML artifact counts are execution/failure evidence, not strict success or raw XML credit. Its fixture now uses the established module-owned filesystem migration location without changing schema versions or weakening any rollback, immutability or concurrency assertion. Focused integration compilation, formatting, Checkstyle and SpotBugs passed (101 tasks, 15 executed/86 up-to-date); the five PostgreSQL cases skipped locally without Docker, so corrected database execution remains open. Existing full-validation and Script Pin/WebSocket gates are retained; this run supplies no Script Pin25/WebSocket16 proof. Other aggregate failures and all activation limits remain open. @@ -73,11 +81,11 @@ The current Unit 1B draft adds Account-owned provisional JOIN/reactivation trans Account runtime admission reads remain a capability/proof blocker. `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are no longer on the public bearer-bypass list, and these two methods plus `GetRealmAccessGrantForRuntime` now deny even the exact Game Session peer with `FAILED_PRECONDITION` before Account data reads because the current requests lack a verified player/tenant or lifecycle target. Missing or wrong peers are denied separately. Unit 1B must implement the typed caller/target contract and consumer propagation before these reads can be enabled; the target boundary is canonical in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). -The #2876 draft adds Account V31 durable issuer, Account UUID, tenant UUID, and membership generations plus an account-local issuance fence. New global registration initializes its persisted Account UUID pair; startup enrolls the exact issuer; approved retained-tenant association enrolls the canonical tenant generation; V34 enrolls retained Account UUID pairs without resetting advanced values and aborts on a half-pair. V33 adds immutable independently sequenced authority events and a shared strict `account-auth-authority-event/v1` Account/Game Session codec with executed positive/negative, ordering, and large-counter vectors. The first-JOIN candidate composes approved retained tenant UUID, V31 membership generation/fence, version-bound roles, V33 event, receipt, audit, and terminal operation in one Account transaction. Replay and abandoned-`PENDING` reconciliation require exact event readback; retained inactive reactivation remains fail-closed without a canonical INACTIVE writer/event. V35 and V36 migrated in hosted PostgreSQL CI; all four V36 repository cases passed in the earlier run, while two V35 timestamp-bind and two JOIN transaction-diagnostic cases failed among 80 Account integration cases. The corrected exact-head Account job subsequently ran `:account-service:integrationTest` and passed, but its success artifact did not include per-test XML, so exact case and skip counts cannot be independently read back for that run; local Docker remains unavailable. Event delivery, Redis projections, Account runtime response, Game Session consumer, fresh-tenant UUID handoff, mixed-version issuer cutover, and complete token issuance remain open. No issued token or runtime response consumes the new state; the membership RPC stays denied and Unit 1B remains provisional. +The #2876 draft adds Account V31 durable issuer, Account UUID, tenant UUID, and membership generations plus an account-local issuance fence. New global registration initializes its persisted Account UUID pair; startup enrolls the exact issuer; approved retained-tenant association enrolls the canonical tenant generation; V34 enrolls retained Account UUID pairs without resetting advanced values and aborts on a half-pair. V33 adds immutable independently sequenced authority events and a shared strict `account-auth-authority-event/v1` Account/Game Session codec with executed positive/negative, ordering, and large-counter vectors. The first-JOIN candidate composes approved retained tenant UUID, V31 membership generation/fence, version-bound roles, V33 event, receipt, audit, and terminal operation in one Account transaction. Replay and abandoned-`PENDING` reconciliation require exact event readback. A local unwired LEFT writer and exact current-INACTIVE reader now exist; without positive canonical current INACTIVE evidence, reactivation still fails closed. V35 and V36 migrated in hosted PostgreSQL CI; all four V36 repository cases passed in the earlier run, while two V35 timestamp-bind and two JOIN transaction-diagnostic cases failed among 80 Account integration cases. The corrected exact-head Account job subsequently ran `:account-service:integrationTest` and passed, but its success artifact did not include per-test XML, so exact case and skip counts cannot be independently read back for that run; local Docker remains unavailable. Event delivery, Redis projections, Account runtime response, Game Session consumer, fresh-tenant UUID handoff, mixed-version issuer cutover, and complete token issuance remain open. No issued token or runtime response consumes the new state; the membership RPC stays denied and Unit 1B remains provisional. The tail now includes the shared Ed25519 compact-JWS primitive and #2911's complete-context component codec for the dedicated Gateway key namespace. The codec preserves exact signed envelope/payload bytes and checks registered receiver, target, lifecycle, authority-map and timestamp shapes; a separate original-source comparison checks Account-to-Gateway correspondence, not current authority or authorization. Gateway runtime issuance and Game Session runtime parsing remain denied: no HMAC/default-key fallback is accepted. Independent key publication/rotation, complete Account issuance/readback and authenticated producer/consumer wiring remain open. Local component proof is not a working signed-context handoff or gameplay admission proof. -Account V32 holds version-bound tenant-role snapshots without backfilling retained memberships. First explicit public JOIN writes `player` with the membership and audit transaction; active membership and abandoned-`PENDING` reconciliation require exact current role and authority-event readback. The earlier reactivation role-update code is not a proved capability: it now fails closed before mutation unless a canonical current INACTIVE event exists, and no such writer is implemented. Prior CI executed 12 PostgreSQL JOIN cases and V32 migration; the corrected-head Account integration task passed, though its success artifact lacks per-test XML for exact method-level counts. Account runtime snapshot and Game Session consumption remain open. +Account V32 holds version-bound tenant-role snapshots without backfilling retained memberships. First explicit public JOIN writes `player` with the membership and audit transaction; active membership and abandoned-`PENDING` reconciliation require exact current role and authority-event readback. The earlier reactivation path remains unproved. The local LEFT candidate preserves its version-bound role set while writing a canonical current INACTIVE event, and the corresponding reader gates reactivation on that exact event, receipt, and pair evidence; PostgreSQL execution is still open. Prior CI executed 12 PostgreSQL JOIN cases and V32 migration; the corrected-head Account integration task passed, though its success artifact lacks per-test XML for exact method-level counts. Account runtime snapshot and Game Session consumption remain open. The #2873 retained tenant bridge has a signed Game Design migration-manifest verifier, immutable owner assertion storage/read, an exact dedicated Account-tenant-migrator gRPC read, and an Account import boundary that recomputes retained V26 source evidence before storing an immutable local mapping. Neither migration auto-creates a pair; both chart Jobs are opt-in and require distinct verified workload certificates, and the runtime membership RPC remains denied. This retained manifest remains separate from fresh identity: #2915 supplies Game Design's fresh creation/readback and Account normal-workload consumer, immutable canonical-UUID association and shared UUID claim index. Account commits that association only after exact operation/request/digest/source/receipt readback, then initializes tenant generation without reset. The earlier seven-failure Game Design fixture run `36791561008` on `6299ea128e174a5a3f55f3478929f5db71d4eb2f` remains incident evidence; it was corrected and superseded by the seven Game Design creation and six Account association PostgreSQL cases executed successfully in exact-head runs `36796087279` and `36804479170`, as recorded above. Game Design's API text no longer describes that old test failure as current missing component proof. A separate Game Session-only persisted tenant identity read/consumer is being prepared on the corrected UUID tail, preserving Account-only creation/migration guards and Game Session's sole catalog/pointer persistence ownership. Its actual catalog intake, retained runtime association, stable selector assignment, mounted-certificate/live handoff and complete admission proof remain open. No numeric Account alias, credential or runtime path is enabled, and retained manifests are not reused for fresh tenants. The wire/digest authority remains [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#fresh-tenant-creation-operation-and-account-readback); Unit 1B remains provisional. @@ -303,7 +311,7 @@ No competing target state is currently recorded. Future design discussion is req | Owner | Current responsibility | Primary contract boundary | | --- | --- | --- | -| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN | Account REST/gRPC APIs; bootstrap/connect-token APIs; runtime membership/grant/entitlement reads; local `JoinPublicProductionMembership` RPC and `POST /auth/bootstrap/join` facade are implemented, while leave remains target-only | +| Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN | Account REST/gRPC APIs; bootstrap/connect-token APIs; runtime membership/grant/entitlement reads; local `JoinPublicProductionMembership` RPC and `POST /auth/bootstrap/join` facade are implemented; an owner-local LEFT component candidate exists without public route authentication or runtime activation | | Common Security | **Current:** JWT/signed-token claims, current-account and tenant access, gameplay-elevated roles, legacy session attestation, current service-identity handling, and downstream caller authorization. **Target:** certificate-derived mTLS workload identity and method allowlists authorize services, while typed `PlayerExecutionContext` carries player scope | `JwtClaims`, `SessionClaims`, session-context helpers, target `PlayerExecutionContext`, certificate-derived mTLS caller identity, caller allowlists, and shared authorization checks; legacy attestation/service-identity code is implementation debt, not target player authority | | TCP Proxy | Telnet transport, hidden bootstrap envelope, bounded connection-local ordered input buffering during edge rebind, disconnect notification, and Telnet close taxonomy | Telnet bridge; `TelnetRoutingBundle`; Game Session `NotifyDisconnect` | | Spring Cloud Gateway | Trusted proxy/first-party handshake validation, signed connect context, stable edge socket/session id, upstream gameplay bridge and rebind | `/ws/game/**`; `TrustedTcpProxyIdentity`; connect-token and first-party context headers | diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigest.java index b942e92a0c..79cf3fd5e6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigest.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigest.java @@ -58,9 +58,18 @@ public static String transitionDigest( if (!receiptStreamKey(accountId, tenantId).equals(streamKey)) { throw new IllegalArgumentException("receiptStreamKey does not match the membership scope"); } - if (!("MEMBERSHIP_JOINED".equals(transition) || "MEMBERSHIP_REACTIVATED".equals(transition))) { + boolean activeTransition = + "MEMBERSHIP_JOINED".equals(transition) || "MEMBERSHIP_REACTIVATED".equals(transition); + boolean leaveTransition = "MEMBERSHIP_LEFT".equals(transition); + if (!activeTransition && !leaveTransition) { throw new IllegalArgumentException("transitionType is not a supported membership receipt"); } + if ((activeTransition && (!"ACTIVE".equals(lifecycleState) || !gameplayAdmissionAllowed)) + || (leaveTransition && (!"INACTIVE".equals(lifecycleState) || gameplayAdmissionAllowed)) + || !"EXPLICIT_JOIN".equals(provenance)) { + throw new IllegalArgumentException( + "transitionType does not match the membership state and provenance"); + } String preimage = "accountMembershipTransitionReceiptVersion=v1\n" diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java index 79a1a7dd26..7ffb4e5855 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java @@ -51,9 +51,13 @@ public record RuntimeMembershipSnapshotDto( throw new IllegalArgumentException( "Runtime membership baseline differs from its tenant tuple"); } - if (membershipExists != "ACTIVE".equals(membershipBaseline.membershipLifecycleState()) - || gameplayAdmissionAllowed != membershipExists - || membershipExists != roles.contains("player")) { + String lifecycleState = membershipBaseline.membershipLifecycleState(); + boolean presentLifecycle = "ACTIVE".equals(lifecycleState) || "INACTIVE".equals(lifecycleState); + boolean activeMembership = "ACTIVE".equals(lifecycleState); + if (membershipExists != presentLifecycle + || gameplayAdmissionAllowed != activeMembership + || (!membershipExists && !roles.isEmpty()) + || (activeMembership && !roles.contains("player"))) { throw new IllegalArgumentException("Runtime membership state is not a supported snapshot"); } requireConsistentSourceEvent( @@ -177,6 +181,7 @@ public record MembershipBaseline( throw new IllegalArgumentException("Runtime membership baseline is not canonical"); } if (!"ACTIVE".equals(membershipLifecycleState) + && !"INACTIVE".equals(membershipLifecycleState) && !"MISSING".equals(membershipLifecycleState)) { throw new IllegalArgumentException("Runtime membership baseline lifecycle is unsupported"); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java index 655c6199b3..bb40559950 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java @@ -14,6 +14,8 @@ import net.firedevops.firemud.accountservice.jooq.tables.records.AccountAuditOutboxRecord; import org.jooq.DSLContext; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; /** Owner-local audit identity, immutable envelope, and durable delivery state. */ @Repository @@ -78,6 +80,26 @@ public Optional findJoinEnvelopeForUpdate( .fetchOptional(this::toEnvelope); } + /** Locks one exact Account LEFT envelope for same-owner-transaction retry proof. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Optional findMembershipLeftEnvelopeForUpdate( + UUID auditEventId, long tenantId) { + if (auditEventId == null || tenantId <= 0) { + throw new IllegalArgumentException("LEFT audit identity and tenant are required"); + } + return dsl.selectFrom(ACCOUNT_AUDIT_OUTBOX) + .where( + ACCOUNT_AUDIT_OUTBOX + .AUDIT_EVENT_ID + .eq(auditEventId) + .and(ACCOUNT_AUDIT_OUTBOX.SCOPE.eq("tenant")) + .and(ACCOUNT_AUDIT_OUTBOX.TENANT_ID.eq(tenantId)) + .and(ACCOUNT_AUDIT_OUTBOX.PRODUCER_SERVICE.eq("account-service")) + .and(ACCOUNT_AUDIT_OUTBOX.EVENT_TYPE.eq("ACCOUNT_MEMBERSHIP_LEFT"))) + .forUpdate() + .fetchOptional(this::toEnvelope); + } + public void markDelivered( UUID auditEventId, String receiptId, String logEventId, boolean minimized) { var update = diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java index 07db5c69f1..09259c8977 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java @@ -11,9 +11,11 @@ import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** - * Retains provisional Account JOIN/reactivation receipts without claiming complete authority proof. + * Retains provisional Account membership-transition receipts without claiming complete authority + * proof. */ @Repository @SuppressFBWarnings( @@ -22,6 +24,7 @@ public class AccountMembershipTransitionReceiptRepository { private static final String MEMBERSHIP_JOINED = "MEMBERSHIP_JOINED"; private static final String MEMBERSHIP_REACTIVATED = "MEMBERSHIP_REACTIVATED"; + private static final String MEMBERSHIP_LEFT = "MEMBERSHIP_LEFT"; private final DSLContext dsl; @@ -29,10 +32,11 @@ public AccountMembershipTransitionReceiptRepository(DSLContext dsl) { this.dsl = dsl; } - /** Appends one provisional receipt inside the surrounding Account JOIN transaction. */ + /** Appends one provisional receipt inside the surrounding Account membership transaction. */ @Transactional(propagation = Propagation.MANDATORY) public MembershipTransitionReceipt appendTransition( AccountTenantMembership membership, String transitionType, String requestId) { + requireOwnerTransaction(); if (membership == null || membership.getAccount() == null || membership.getAccount().getId() == null @@ -42,15 +46,7 @@ public MembershipTransitionReceipt appendTransition( long accountId = membership.getAccount().getId(); long tenantId = membership.getTenantId(); long membershipId = membership.getId(); - if (!MEMBERSHIP_JOINED.equals(transitionType) - && !MEMBERSHIP_REACTIVATED.equals(transitionType)) { - throw new IllegalArgumentException("Membership transition type is unsupported"); - } - if (!"ACTIVE".equals(membership.getLifecycleState()) - || !membership.isGameplayAdmissionAllowed() - || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance())) { - throw new IllegalArgumentException("JOIN receipt requires its committed active state"); - } + requireTransitionState(membership, transitionType); String streamKey = MembershipTransitionReceiptDigest.receiptStreamKey(accountId, tenantId); UUID receiptId = MembershipTransitionReceiptDigest.receiptIdForRequest(requestId); @@ -142,8 +138,10 @@ public Optional findLatestReceipt(long accountId, l Long currentMembershipId = snapshot.currentMembershipId(); if (currentMembershipId != null && (currentMembershipId.longValue() != receipt.membershipId() - || !"ACTIVE".equals(snapshot.currentLifecycleState()) - || !snapshot.currentAdmissionAllowed() + || !receiptStateMatches( + receipt.transitionType(), + snapshot.currentLifecycleState(), + snapshot.currentAdmissionAllowed()) || snapshot.currentMembershipVersion() != snapshot.receiptMembershipVersion() || snapshot.currentAuthorityGeneration() != snapshot.receiptAuthorityGeneration() || !"EXPLICIT_JOIN".equals(snapshot.currentAuthorityProvenance()))) { @@ -153,6 +151,119 @@ public Optional findLatestReceipt(long accountId, l return Optional.of(receipt); } + /** + * Reads one immutable transition receipt by its globally unique request ID without requiring it + * to remain the current receipt. This supports exact, non-authorizing replay after a later + * membership transition; callers must separately prove the matching event and audit envelope. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Optional findByRequestId(String requestId) { + requireOwnerTransaction(); + if (requestId == null || requestId.isBlank()) { + throw new IllegalArgumentException("Account membership request ID is required"); + } + Record row = + dsl.fetchOne( + "SELECT r.receipt_stream_key, r.receipt_sequence, r.account_id, r.tenant_id, " + + "h.receipt_stream_key AS head_stream_key, " + + "h.last_receipt_sequence AS head_receipt_sequence, r.evidence_status, " + + "r.transition_type, r.request_id, r.membership_id, r.membership_lifecycle_state, " + + "r.gameplay_admission_allowed, r.membership_version, " + + "r.membership_authority_generation, r.authority_provenance, r.receipt_id, r.receipt_digest " + + "FROM account_membership_transition_receipts r " + + "JOIN account_membership_transition_receipt_stream_heads h " + + "ON h.account_id = r.account_id AND h.tenant_id = r.tenant_id " + + "WHERE r.request_id = ?", + requestId); + if (row == null) { + return Optional.empty(); + } + String streamKey = row.get("receipt_stream_key", String.class); + Long sequence = row.get("receipt_sequence", Long.class); + Long headSequence = row.get("head_receipt_sequence", Long.class); + String headStreamKey = row.get("head_stream_key", String.class); + Long accountId = row.get("account_id", Long.class); + Long tenantId = row.get("tenant_id", Long.class); + String evidenceStatus = row.get("evidence_status", String.class); + String transitionType = row.get("transition_type", String.class); + String retainedRequestId = row.get("request_id", String.class); + Long membershipId = row.get("membership_id", Long.class); + String lifecycleState = row.get("membership_lifecycle_state", String.class); + Boolean admissionAllowed = row.get("gameplay_admission_allowed", Boolean.class); + Long membershipVersion = row.get("membership_version", Long.class); + Long authorityGeneration = row.get("membership_authority_generation", Long.class); + String authorityProvenance = row.get("authority_provenance", String.class); + UUID receiptId = row.get("receipt_id", UUID.class); + String receiptDigest = row.get("receipt_digest", String.class); + if (sequence == null + || sequence <= 0L + || headSequence == null + || headSequence < sequence + || accountId == null + || accountId <= 0L + || tenantId == null + || tenantId <= 0L + || !requestId.equals(retainedRequestId) + || membershipId == null + || membershipId <= 0L + || lifecycleState == null + || admissionAllowed == null + || membershipVersion == null + || membershipVersion <= 0L + || authorityGeneration == null + || authorityGeneration <= 0L + || authorityProvenance == null + || receiptId == null + || receiptDigest == null + || !MembershipTransitionReceiptDigest.receiptStreamKey(accountId, tenantId) + .equals(streamKey) + || !streamKey.equals(headStreamKey) + || !MembershipTransitionReceiptDigest.EVIDENCE_STATUS.equals(evidenceStatus) + || !receiptId.equals(MembershipTransitionReceiptDigest.receiptIdForRequest(requestId))) { + throw new IllegalStateException( + "Account membership transition receipt scope is inconsistent"); + } + String expectedDigest = + MembershipTransitionReceiptDigest.transitionDigest( + streamKey, + sequence, + receiptId, + transitionType, + requestId, + accountId, + tenantId, + membershipId, + lifecycleState, + admissionAllowed, + membershipVersion, + authorityGeneration, + authorityProvenance); + if (!expectedDigest.equals(receiptDigest)) { + throw new IllegalStateException( + "Account membership transition receipt digest is inconsistent"); + } + MembershipTransitionReceipt receipt = + new MembershipTransitionReceipt( + streamKey, + sequence, + receiptId, + receiptDigest, + evidenceStatus, + transitionType, + requestId, + membershipId); + return Optional.of( + new TransitionReceiptEvidence( + receipt, + accountId, + tenantId, + lifecycleState, + admissionAllowed, + membershipVersion, + authorityGeneration, + authorityProvenance)); + } + /** * Fail-closes a new row when prior history exists or no versioned restoration path is defined. */ @@ -358,6 +469,46 @@ private boolean hasPriorMembershipHistory(long accountId, long tenantId) { return Boolean.TRUE.equals(hasHistory); } + private static void requireTransitionState( + AccountTenantMembership membership, String transitionType) { + if (MEMBERSHIP_JOINED.equals(transitionType) || MEMBERSHIP_REACTIVATED.equals(transitionType)) { + if (!"ACTIVE".equals(membership.getLifecycleState()) + || !membership.isGameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance())) { + throw new IllegalArgumentException("JOIN receipt requires its committed active state"); + } + return; + } + if (MEMBERSHIP_LEFT.equals(transitionType)) { + if (!"INACTIVE".equals(membership.getLifecycleState()) + || membership.isGameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance())) { + throw new IllegalArgumentException( + "LEAVE receipt requires its committed inactive non-admitting state"); + } + return; + } + throw new IllegalArgumentException("Membership transition type is unsupported"); + } + + private static boolean receiptStateMatches( + String transitionType, String lifecycleState, boolean gameplayAdmissionAllowed) { + return ((MEMBERSHIP_JOINED.equals(transitionType) + || MEMBERSHIP_REACTIVATED.equals(transitionType)) + && "ACTIVE".equals(lifecycleState) + && gameplayAdmissionAllowed) + || (MEMBERSHIP_LEFT.equals(transitionType) + && "INACTIVE".equals(lifecycleState) + && !gameplayAdmissionAllowed); + } + + private void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account membership receipt access requires an active owner transaction"); + } + } + private record ReceiptSnapshot( MembershipTransitionReceipt receipt, Long currentMembershipId, @@ -368,4 +519,15 @@ private record ReceiptSnapshot( String currentAuthorityProvenance, long receiptMembershipVersion, long receiptAuthorityGeneration) {} + + /** Immutable receipt bytes plus the state needed to bind it to its original event. */ + public record TransitionReceiptEvidence( + MembershipTransitionReceipt receipt, + long accountId, + long tenantId, + String lifecycleState, + boolean gameplayAdmissionAllowed, + long membershipVersion, + long membershipAuthorityGeneration, + String authorityProvenance) {} } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index b7d4cb67b7..9081c9182b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -308,6 +308,168 @@ public PositiveMembershipSnapshot readCurrentPairBoundPositiveMembershipSnapshot return positive; } + /** + * Reads exact current retained INACTIVE evidence without enrolling or authorizing the pair. The + * positive immutable receipt, closed event, current generation/fence and existing pair row must + * all agree under the same Account owner-row fence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public RuntimeMembershipSnapshotDto readCurrentPairBoundInactiveMembershipSnapshot( + long accountId, long legacyTenantId) { + requireActiveOwnerTransaction(); + if (accountId <= 0L || legacyTenantId <= 0L) { + throw new IllegalArgumentException("Account and retained tenant identities must be positive"); + } + joinOperationRepository.lockAccount(accountId); + Identity identity = resolveIdentity(accountId, legacyTenantId); + JoinMembershipProof membership = + membershipRepository + .findJoinProofForUpdate(accountId, legacyTenantId) + .orElseThrow( + () -> new IllegalStateException("Current Account membership row is absent")); + if (membership.accountId() != accountId + || membership.tenantId() != legacyTenantId + || membership.membershipId() <= 0L + || membership.membershipVersion() <= 0L + || membership.membershipAuthorityGeneration() <= 0L + || !"INACTIVE".equals(membership.lifecycleState()) + || membership.gameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.authorityProvenance())) { + throw new IllegalStateException( + "Current Account membership is not an explicit retained inactive membership"); + } + + RoleSnapshot roles = + roleSnapshotRepository + .findForUpdate( + accountId, + legacyTenantId, + membership.membershipId(), + membership.membershipVersion()) + .orElseThrow( + () -> + new IllegalStateException( + "Current Account membership role snapshot is absent")); + List exactRoles; + try { + exactRoles = + AccountTenantMembershipRoleSnapshotRepository.requireCanonicalRoleSet(roles.roles()); + } catch (RuntimeException exception) { + throw new IllegalStateException("Current Account role snapshot is not canonical", exception); + } + if (roles.accountId() != accountId + || roles.tenantId() != legacyTenantId + || roles.membershipId() != membership.membershipId() + || roles.snapshotVersion() != membership.membershipVersion()) { + throw new IllegalStateException( + "Current Account role snapshot differs from its exact inactive membership"); + } + + MembershipTransitionReceipt receipt = + transitionReceiptRepository + .findLatestReceipt(accountId, legacyTenantId) + .orElseThrow( + () -> new IllegalStateException("Current inactive membership receipt is absent")); + if (!MembershipTransitionReceiptDigest.receiptStreamKey(accountId, legacyTenantId) + .equals(receipt.receiptStreamKey()) + || receipt.receiptSequence() <= 0L + || receipt.receiptId() == null + || receipt.receiptDigest() == null + || !MembershipTransitionReceiptDigest.EVIDENCE_STATUS.equals(receipt.evidenceStatus()) + || !"MEMBERSHIP_LEFT".equals(receipt.transitionType()) + || receipt.requestId() == null + || receipt.requestId().isBlank() + || receipt.membershipId() != membership.membershipId()) { + throw new IllegalStateException( + "Current inactive membership lacks its exact positive LEFT receipt"); + } + + CompositeSnapshot authoritySnapshot = readSnapshot(identity); + ScopeState membershipAuthority = only(authoritySnapshot.memberships(), "membership"); + requireMatchingFence(authoritySnapshot, membershipAuthority, identity.accountUuid()); + if (membershipAuthority.generation() != membership.membershipAuthorityGeneration()) { + throw new IllegalStateException( + "Current inactive membership differs from its V31 authority generation"); + } + List upstreamCheckpoints = + readBaselineUpstreamCheckpoints(identity, authoritySnapshot); + String streamKey = membershipStreamKey(identity); + Checkpoint checkpoint = + authorityOutboxRepository + .readCheckpoint(streamKey) + .orElseThrow( + () -> + new IllegalStateException("Current inactive membership has no V33 checkpoint")); + if (checkpoint.outboxSequence() <= 0L) { + throw new IllegalStateException("Current inactive membership checkpoint is not positive"); + } + Event event = + authorityOutboxRepository + .findEvent(streamKey, checkpoint.outboxSequence()) + .orElseThrow( + () -> new IllegalStateException("Current inactive checkpoint has no event")); + if (!checkpointMatches(checkpoint, event)) { + throw new IllegalStateException("Current inactive checkpoint differs from its event"); + } + MembershipEvent verified = verifyStoredEvent(event, identity, event.requestId()); + if (!receipt.requestId().equals(verified.requestId())) { + throw new IllegalStateException("Current inactive receipt differs from its latest event"); + } + requireCurrentMembershipEvent( + identity, + membership.membershipId(), + membership.lifecycleState(), + membership.gameplayAdmissionAllowed(), + membership.membershipVersion(), + membership.membershipAuthorityGeneration(), + membership.authorityProvenance(), + roles, + receipt.requestId(), + true, + authoritySnapshot); + + PairAuthority pair = + pairAuthorityRepository + .readForUpdate(identity.accountUuid(), identity.tenantUuid()) + .orElseThrow( + () -> + new IllegalStateException( + "Current inactive membership pair authority is absent")); + if (!verifiedProvenance(identity).equals(pair.provenance()) + || !pair.membershipExists() + || pair.membershipVersion() != membership.membershipVersion() + || pair.membershipAuthorityGeneration() != membership.membershipAuthorityGeneration() + || pair.lastEventSequence() != checkpoint.outboxSequence() + || !checkpoint.sourceEventId().equals(pair.lastEventId()) + || !checkpoint.sourceEventDigest().equals(pair.lastEventDigest()) + || !pair.lastTransitionInvalidated()) { + throw new IllegalStateException( + "Current inactive membership differs from its durable pair authority"); + } + + List checkpoints = new ArrayList<>(upstreamCheckpoints); + checkpoints.add( + new OutboxCheckpointEntry(streamKey, Long.toString(checkpoint.outboxSequence()))); + return new RuntimeMembershipSnapshotDto( + identity.accountUuid().toString(), + identity.tenantUuid().toString(), + identity.accountUuid().toString(), + identity.tenantUuid().toString(), + true, + false, + new RuntimeMembershipSnapshotDto.MembershipBaseline( + "INACTIVE", + membershipVersionMap(verified, identity), + verified.membershipAuthorityGeneration()), + exactRoles, + verified.authorityTuple(), + verified.issuanceFence(), + Instant.now(), + orderedCheckpoints(checkpoints), + List.of(sourceEvidence(checkpoint, event)), + verified); + } + /** * Reads only an already-existing positive membership for exact canonical Account and tenant * UUIDs, under the Account owner transaction and row fence. @@ -417,7 +579,13 @@ public RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot( throw new IllegalArgumentException("Account and retained tenant identities must be positive"); } preparePairAuthorityForRuntimeSnapshot(accountId, legacyTenantId); - if (membershipRepository.findJoinProofForUpdate(accountId, legacyTenantId).isPresent()) { + Optional currentMembership = + membershipRepository.findJoinProofForUpdate(accountId, legacyTenantId); + if (currentMembership.isPresent() + && "INACTIVE".equals(currentMembership.orElseThrow().lifecycleState())) { + return readCurrentPairBoundInactiveMembershipSnapshot(accountId, legacyTenantId); + } + if (currentMembership.isPresent()) { PositiveMembershipSnapshot positive = readCurrentPairBoundPositiveMembershipSnapshot(accountId, legacyTenantId); return new RuntimeMembershipSnapshotDto( @@ -781,8 +949,8 @@ public void preparePairAuthorityForJoin(long accountId, long legacyTenantId) { * *

A never-joined pair reuses JOIN's committed absence enrollment, then proves the resulting * sequence-zero snapshot. An existing membership is enrolled only through its exact current - * active receipt/event proof and is read back against the pair row. Inactive, unproved, or - * contradictory history remains denied; this method does not mutate membership or event history. + * active or inactive receipt/event proof and is read back against the pair row. No retained + * inactive path enrolls or changes membership/event history. */ @Transactional(propagation = Propagation.MANDATORY) public void preparePairAuthorityForRuntimeSnapshot(long accountId, long legacyTenantId) { @@ -793,12 +961,19 @@ public void preparePairAuthorityForRuntimeSnapshot(long accountId, long legacyTe // Keep the same lock order as JOIN before resolving identity or inspecting retained history. joinOperationRepository.lockAccount(accountId); resolveIdentity(accountId, legacyTenantId); - if (membershipRepository.findJoinProofForUpdate(accountId, legacyTenantId).isEmpty()) { + Optional currentMembership = + membershipRepository.findJoinProofForUpdate(accountId, legacyTenantId); + if (currentMembership.isEmpty()) { preparePairAuthorityForJoin(accountId, legacyTenantId); readNeverJoinedMembershipSnapshot(accountId, legacyTenantId); return; } + if ("INACTIVE".equals(currentMembership.orElseThrow().lifecycleState())) { + readCurrentPairBoundInactiveMembershipSnapshot(accountId, legacyTenantId); + return; + } + enrollProvenRetainedActivePair(accountId, legacyTenantId); readCurrentPairBoundPositiveMembershipSnapshot(accountId, legacyTenantId); } @@ -981,7 +1156,7 @@ public Checkpoint publishNewMembershipChange( "New Account membership acquired V33 authority-event history before publication"); } Checkpoint checkpoint = - appendAndReadBack(identity, requestId, membership, snapshot, false, true); + appendAndReadBack(identity, requestId, membership, snapshot, false, true, false); PairAuthority committed = pairAuthorityRepository.commitTransition( absenceBaseline, @@ -1046,7 +1221,7 @@ public Checkpoint publishReactivatedMembershipChange( "Committed Account membership tuple differs from the reactivation candidate"); } Checkpoint checkpoint = - appendAndReadBack(identity, requestId, membership, committedCandidate, true, false); + appendAndReadBack(identity, requestId, membership, committedCandidate, true, false, false); PairAuthority committed = pairAuthorityRepository.commitTransition( priorPair, @@ -1065,6 +1240,72 @@ public Checkpoint publishReactivatedMembershipChange( return checkpoint; } + /** Compare-and-advances an existing active member to its committed non-admitting LEFT event. */ + @Transactional(propagation = Propagation.MANDATORY) + public Checkpoint publishLeftMembershipChange( + long accountId, long legacyTenantId, String requestId, AccountTenantMembership membership) { + requireActiveOwnerTransaction(); + Identity identity = resolveIdentity(accountId, legacyTenantId); + requireMembershipIdentity(accountId, legacyTenantId, membership); + if (!"INACTIVE".equals(membership.getLifecycleState()) + || membership.isGameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance())) { + throw new IllegalStateException("LEFT Account membership is not inactive and explicit"); + } + long expectedPriorVersion = decrementPositive(membership.getMembershipVersion()); + long expectedPriorGeneration = decrementPositive(membership.getMembershipAuthorityGeneration()); + PairAuthority priorPair = + pairAuthorityRepository + .readForUpdate(identity.accountUuid(), identity.tenantUuid()) + .orElseThrow(() -> new IllegalStateException("LEFT membership has no pair authority")); + if (!verifiedProvenance(identity).equals(priorPair.provenance()) + || !priorPair.membershipExists() + || priorPair.membershipVersion() != expectedPriorVersion + || priorPair.membershipAuthorityGeneration() != expectedPriorGeneration + || priorPair.lastEventSequence() <= 0L) { + throw new IllegalStateException("LEFT membership differs from its prior pair authority"); + } + CompositeSnapshot beforeAdvance = readSnapshot(identity); + ScopeState currentMembership = only(beforeAdvance.memberships(), "membership"); + requireMatchingFence(beforeAdvance, currentMembership, identity.accountUuid()); + if (currentMembership.generation() != expectedPriorGeneration) { + throw new IllegalStateException( + "Embedded and canonical Account membership generations differ at LEFT"); + } + ScopeState advanced = + authorityGenerationRepository.advance(currentMembership, beforeAdvance.issuanceFence()); + if (advanced.generation() != membership.getMembershipAuthorityGeneration()) { + throw new IllegalStateException( + "Account membership authority generation did not advance at LEFT"); + } + CompositeSnapshot committedCandidate = readSnapshot(identity); + ScopeState committedMembership = only(committedCandidate.memberships(), "membership"); + requireMatchingFence(committedCandidate, committedMembership, identity.accountUuid()); + if (committedMembership.generation() != membership.getMembershipAuthorityGeneration()) { + throw new IllegalStateException( + "Committed Account membership tuple differs from the LEFT candidate"); + } + Checkpoint checkpoint = + appendAndReadBack(identity, requestId, membership, committedCandidate, true, false, true); + PairAuthority committed = + pairAuthorityRepository.commitTransition( + priorPair, + new PairTransition( + true, + checkpoint.outboxSequence(), + checkpoint.sourceEventId(), + checkpoint.sourceEventDigest(), + true)); + if (committed.membershipVersion() != membership.getMembershipVersion() + || committed.membershipAuthorityGeneration() + != membership.getMembershipAuthorityGeneration() + || !committed.lastTransitionInvalidated()) { + throw new IllegalStateException( + "LEFT membership pair authority readback differs from its event"); + } + return checkpoint; + } + /** * Verifies a JOINED operation against its exact immutable event, even after later stream events. */ @@ -1120,9 +1361,14 @@ private Checkpoint appendAndReadBack( AccountTenantMembership membership, CompositeSnapshot snapshot, boolean callerBoundAuthorityInvalidated, - boolean newMembership) { - requirePositive(requestId, "JOIN request ID"); - requireActiveMembership(membership); + boolean newMembership, + boolean inactiveMembership) { + requirePositive(requestId, "membership transition request ID"); + if (inactiveMembership) { + requireInactiveMembership(membership); + } else { + requireActiveMembership(membership); + } ScopeState issuer = snapshot.issuer(); ScopeState account = snapshot.account(); ScopeState tenant = only(snapshot.tenants(), "tenant"); @@ -1137,10 +1383,11 @@ private Checkpoint appendAndReadBack( "A new Account membership cannot reuse a retained generation"); } if (!newMembership && !callerBoundAuthorityInvalidated) { - throw new IllegalStateException("Membership reactivation must invalidate caller authority"); + throw new IllegalStateException( + "Membership lifecycle transition must invalidate caller authority"); } readBaselineUpstreamCheckpoints(identity, snapshot); - RoleSnapshot roles = requireRoleSnapshot(identity, membership); + RoleSnapshot roles = requireRoleSnapshot(identity, membership, inactiveMembership); String streamKey = membershipStreamKey(identity); String expectedEventId = eventIdForRequest(requestId); MembershipEvent[] candidate = new MembershipEvent[1]; @@ -1483,9 +1730,10 @@ private OutboxSourceEvidence sourceEvidence(Checkpoint checkpoint, Event event) new String(event.payload(), StandardCharsets.UTF_8)); } - private RoleSnapshot requireRoleSnapshot(Identity identity, AccountTenantMembership membership) { + private RoleSnapshot requireRoleSnapshot( + Identity identity, AccountTenantMembership membership, boolean inactiveMembership) { if (membership.getId() == null || membership.getMembershipVersion() <= 0L) { - throw new IllegalStateException("Account JOIN membership role identity is incomplete"); + throw new IllegalStateException("Account membership role identity is incomplete"); } RoleSnapshot snapshot = roleSnapshotRepository @@ -1494,15 +1742,29 @@ private RoleSnapshot requireRoleSnapshot(Identity identity, AccountTenantMembers identity.legacyTenantId(), membership.getId(), membership.getMembershipVersion()) - .orElseThrow(() -> new IllegalStateException("Account JOIN role snapshot is absent")); + .orElseThrow( + () -> new IllegalStateException("Account membership role snapshot is absent")); + List exactRoles; + try { + exactRoles = + AccountTenantMembershipRoleSnapshotRepository.requireCanonicalRoleSet(snapshot.roles()); + } catch (RuntimeException exception) { + throw new IllegalStateException( + "Account membership role snapshot is not canonical", exception); + } if (snapshot.accountId() != identity.accountId() || snapshot.tenantId() != identity.legacyTenantId() || snapshot.membershipId() != membership.getId() || snapshot.snapshotVersion() != membership.getMembershipVersion() - || !snapshot.roles().contains("player")) { - throw new IllegalStateException("Account JOIN role snapshot differs from its membership"); + || (!inactiveMembership && !exactRoles.contains("player"))) { + throw new IllegalStateException("Account role snapshot differs from its membership"); } - return snapshot; + return new RoleSnapshot( + snapshot.accountId(), + snapshot.tenantId(), + snapshot.membershipId(), + snapshot.snapshotVersion(), + exactRoles); } private CompositeSnapshot readSnapshot(Identity identity) { @@ -1621,6 +1883,17 @@ private void requireActiveMembership(AccountTenantMembership membership) { } } + private void requireInactiveMembership(AccountTenantMembership membership) { + if (membership.getMembershipVersion() <= 0L + || membership.getMembershipAuthorityGeneration() <= 0L + || !"INACTIVE".equals(membership.getLifecycleState()) + || membership.isGameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance())) { + throw new IllegalStateException( + "LEFT event requires a persisted inactive explicit membership"); + } + } + private String membershipStreamKey(Identity identity) { return membershipStreamKey(identity.accountUuid(), identity.tenantUuid()); } @@ -1662,7 +1935,7 @@ private String decimal(long value) { private long decrementPositive(long value) { if (value <= 1L) { - throw new IllegalStateException("Reactivation requires prior positive membership history"); + throw new IllegalStateException("Membership lifecycle requires prior positive history"); } return value - 1L; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipLifecycleService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipLifecycleService.java new file mode 100644 index 0000000000..312a4c54d9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipLifecycleService.java @@ -0,0 +1,426 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository.TransitionReceiptEvidence; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +/** + * Unwired, Account-owned membership lifecycle primitive. Numeric scope inputs identify rows only; + * this class provides no caller authentication, route, credential issuance, or runtime dispatch. + */ +@Service +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected Account repositories and transaction manager are private collaborators.") +public final class AccountMembershipLifecycleService { + private static final String MEMBERSHIP_LEFT = "MEMBERSHIP_LEFT"; + private static final String LEFT_AUDIT_TYPE = "ACCOUNT_MEMBERSHIP_LEFT"; + private static final JsonMapper AUDIT_JSON = JsonMapper.builder().build(); + + private final AccountJoinOperationRepository joinOperationRepository; + private final AccountRepository accountRepository; + private final AccountTenantIdentityResolver tenantIdentityResolver; + private final AccountTenantMembershipRepository membershipRepository; + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository; + private final AccountMembershipTransitionReceiptRepository receiptRepository; + private final AccountAuthorityOutboxRepository authorityOutboxRepository; + private final AccountAuditOutboxRepository auditOutboxRepository; + private final AccountMembershipAuthorityEventProducer authorityEventProducer; + private final TransactionTemplate ownerTransaction; + + public AccountMembershipLifecycleService( + AccountJoinOperationRepository joinOperationRepository, + AccountRepository accountRepository, + AccountTenantIdentityResolver tenantIdentityResolver, + AccountTenantMembershipRepository membershipRepository, + AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository, + AccountMembershipTransitionReceiptRepository receiptRepository, + AccountAuthorityOutboxRepository authorityOutboxRepository, + AccountAuditOutboxRepository auditOutboxRepository, + AccountMembershipAuthorityEventProducer authorityEventProducer, + PlatformTransactionManager transactionManager) { + this.joinOperationRepository = Objects.requireNonNull(joinOperationRepository); + this.accountRepository = Objects.requireNonNull(accountRepository); + this.tenantIdentityResolver = Objects.requireNonNull(tenantIdentityResolver); + this.membershipRepository = Objects.requireNonNull(membershipRepository); + this.roleSnapshotRepository = Objects.requireNonNull(roleSnapshotRepository); + this.receiptRepository = Objects.requireNonNull(receiptRepository); + this.authorityOutboxRepository = Objects.requireNonNull(authorityOutboxRepository); + this.auditOutboxRepository = Objects.requireNonNull(auditOutboxRepository); + this.authorityEventProducer = Objects.requireNonNull(authorityEventProducer); + this.ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + /** + * Commits an internal owner-local LEFT using one stable request ID. The returned provisional + * receipt identifies that immutable operation only; it is not current authority or authorization. + */ + public MembershipTransitionReceipt leave(long accountId, long legacyTenantId, String requestId) { + if (accountId <= 0L || legacyTenantId <= 0L) { + throw new IllegalArgumentException("Account and retained tenant identities must be positive"); + } + requireRequestId(requestId); + return Objects.requireNonNull( + ownerTransaction.execute( + status -> leaveInOwnerTransaction(accountId, legacyTenantId, requestId)), + "Account LEFT transaction returned no immutable receipt"); + } + + private MembershipTransitionReceipt leaveInOwnerTransaction( + long accountId, long legacyTenantId, String requestId) { + joinOperationRepository.lockAccount(accountId); + CanonicalScope scope = resolveCanonicalScope(accountId, legacyTenantId); + + Optional priorReceipt = receiptRepository.findByRequestId(requestId); + if (priorReceipt.isPresent()) { + TransitionReceiptEvidence evidence = priorReceipt.orElseThrow(); + if (evidence.accountId() != accountId + || evidence.tenantId() != legacyTenantId + || !MEMBERSHIP_LEFT.equals(evidence.receipt().transitionType())) { + throw new IllegalStateException("Membership request ID was reused for another operation"); + } + return requireExactLeftReplay(scope, evidence); + } + if (joinOperationRepository.find(requestId).isPresent()) { + throw new IllegalStateException("Membership request ID conflicts with an existing JOIN"); + } + + String streamKey = membershipStreamKey(scope.accountUuid(), scope.tenantUuid()); + if (authorityOutboxRepository.findEvent(streamKey, requestId).isPresent()) { + throw new IllegalStateException("LEFT request has an event without its matching receipt"); + } + UUID auditEventId = leftAuditId(requestId); + if (auditOutboxRepository + .findMembershipLeftEnvelopeForUpdate(auditEventId, legacyTenantId) + .isPresent()) { + throw new IllegalStateException("LEFT request has an audit envelope without its receipt"); + } + + AccountMembershipAuthorityEventProducer.PositiveMembershipSnapshot active = + authorityEventProducer.readCurrentPairBoundPositiveMembershipSnapshot( + accountId, legacyTenantId); + if (!scope.accountUuid().toString().equals(active.accountId()) + || !scope.tenantUuid().toString().equals(active.tenantId()) + || !active.membershipExists() + || !"ACTIVE".equals(active.membershipLifecycleState()) + || !active.gameplayAdmissionAllowed()) { + throw new IllegalStateException("LEFT requires complete current positive ACTIVE membership"); + } + + AccountTenantMembership membership = + membershipRepository + .findByAccountIdAndTenantId(accountId, legacyTenantId) + .orElseThrow( + () -> new IllegalStateException("Current Account membership row is absent")); + if (membership.getId() == null + || membership.getId() <= 0L + || membership.getAccount() == null + || membership.getAccount().getId() == null + || membership.getAccount().getId() != accountId + || membership.getTenantId() != legacyTenantId + || !"ACTIVE".equals(membership.getLifecycleState()) + || !membership.isGameplayAdmissionAllowed() + || membership.getMembershipVersion() + != Long.parseLong(active.membershipVersion().get(scope.tenantUuid().toString())) + || membership.getMembershipAuthorityGeneration() + != Long.parseLong(active.membershipAuthorityGeneration()) + || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance())) { + throw new IllegalStateException("Current Account membership differs from its positive proof"); + } + RoleSnapshot roles = + roleSnapshotRepository + .findForUpdate( + accountId, legacyTenantId, membership.getId(), membership.getMembershipVersion()) + .orElseThrow( + () -> new IllegalStateException("Current Account role snapshot is absent")); + if (!active.roles().equals(roles.roles())) { + throw new IllegalStateException( + "Current Account role snapshot differs from its positive proof"); + } + + long nextVersion = increment(membership.getMembershipVersion(), "membership version"); + long nextGeneration = + increment(membership.getMembershipAuthorityGeneration(), "membership authority generation"); + membership.setLifecycleState("INACTIVE"); + membership.setGameplayAdmissionAllowed(false); + membership.setMembershipVersion(nextVersion); + membership.setMembershipAuthorityGeneration(nextGeneration); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + membershipRepository.saveAndFlush(membership); + roleSnapshotRepository.replace(membership, nextVersion, roles.roles()); + + var checkpoint = + authorityEventProducer.publishLeftMembershipChange( + accountId, legacyTenantId, requestId, membership); + if (checkpoint == null || checkpoint.outboxSequence() <= 0L) { + throw new IllegalStateException("Account LEFT event checkpoint readback is incomplete"); + } + MembershipTransitionReceipt receipt = + receiptRepository.appendTransition(membership, MEMBERSHIP_LEFT, requestId); + Event leftEvent = + authorityOutboxRepository + .findEvent(streamKey, requestId) + .orElseThrow(() -> new IllegalStateException("Account LEFT event readback is absent")); + TransitionReceiptEvidence leftReceiptEvidence = + new TransitionReceiptEvidence( + receipt, + accountId, + legacyTenantId, + membership.getLifecycleState(), + membership.isGameplayAdmissionAllowed(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + membership.getAuthorityProvenance()); + MembershipEvent verifiedLeftEvent = verifyLeftEvent(scope, leftReceiptEvidence, leftEvent); + if (leftEvent.outboxSequence() != checkpoint.outboxSequence() + || !leftEvent.eventId().equals(checkpoint.sourceEventId()) + || !leftEvent.eventDigest().equals(checkpoint.sourceEventDigest()) + || !roles.roles().equals(verifiedLeftEvent.roles())) { + throw new IllegalStateException("Account LEFT event differs from its committed checkpoint"); + } + String payload = + leftAuditPayload(scope, receipt, leftEvent, leftReceiptEvidence, verifiedLeftEvent); + AccountAuditEnvelope appended = + auditOutboxRepository.append( + auditEventId, "tenant", legacyTenantId, LEFT_AUDIT_TYPE, payload); + requireExactAuditEnvelope( + scope, + auditEventId, + legacyTenantId, + payload, + appended, + auditOutboxRepository + .findMembershipLeftEnvelopeForUpdate(auditEventId, legacyTenantId) + .orElseThrow(() -> new IllegalStateException("Account LEFT audit readback is absent"))); + return receipt; + } + + private MembershipTransitionReceipt requireExactLeftReplay( + CanonicalScope scope, TransitionReceiptEvidence evidence) { + MembershipTransitionReceipt receipt = evidence.receipt(); + if (!"INACTIVE".equals(evidence.lifecycleState()) + || evidence.gameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(evidence.authorityProvenance())) { + throw new IllegalStateException("Stored LEFT receipt state is contradictory"); + } + String streamKey = membershipStreamKey(scope.accountUuid(), scope.tenantUuid()); + Event storedEvent = + authorityOutboxRepository + .findEvent(streamKey, receipt.requestId()) + .orElseThrow(() -> new IllegalStateException("Stored LEFT receipt has no exact event")); + MembershipEvent event = verifyLeftEvent(scope, evidence, storedEvent); + UUID auditEventId = leftAuditId(receipt.requestId()); + String payload = leftAuditPayload(scope, receipt, storedEvent, evidence, event); + AccountAuditEnvelope audit = + auditOutboxRepository + .findMembershipLeftEnvelopeForUpdate(auditEventId, scope.legacyTenantId()) + .orElseThrow(() -> new IllegalStateException("Stored LEFT receipt has no exact audit")); + requireExactAuditEnvelope(scope, auditEventId, scope.legacyTenantId(), payload, audit, audit); + return receipt; + } + + private MembershipEvent verifyLeftEvent( + CanonicalScope scope, TransitionReceiptEvidence evidence, Event storedEvent) { + MembershipTransitionReceipt receipt = evidence.receipt(); + MembershipEvent event; + try { + event = + MembershipAuthorityEventV1Codec.verify( + new String(storedEvent.payload(), StandardCharsets.UTF_8)); + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored LEFT authority event is invalid", exception); + } + String streamKey = membershipStreamKey(scope.accountUuid(), scope.tenantUuid()); + String tenantUuid = scope.tenantUuid().toString(); + if (!storedEvent.outboxStreamKey().equals(streamKey) + || !storedEvent.requestId().equals(receipt.requestId()) + || !storedEvent.eventId().equals(event.eventId()) + || !storedEvent.eventDigest().equals(event.eventDigest()) + || !event.outboxStreamKey().equals(streamKey) + || !event.accountId().equals(scope.accountUuid().toString()) + || !event.tenantId().equals(tenantUuid) + || !event.requestId().equals(receipt.requestId()) + || !event.eventId().equals(expectedEventId(receipt.requestId())) + || !Long.toString(storedEvent.outboxSequence()).equals(event.outboxSequence()) + || !java.util.Arrays.equals(storedEvent.payload(), event.canonicalJsonUtf8()) + || !"INACTIVE".equals(event.membershipLifecycleState()) + || event.gameplayAdmissionAllowed() + || !event.callerBoundAuthorityInvalidated() + || !Map.of(tenantUuid, Long.toString(evidence.membershipVersion())) + .equals(event.membershipVersion()) + || !Long.toString(evidence.membershipAuthorityGeneration()) + .equals(event.membershipAuthorityGeneration()) + || !Long.toString(evidence.membershipAuthorityGeneration()) + .equals(event.authorityTuple().membershipAuthorityGeneration().get(tenantUuid)) + || event.roles() == null) { + throw new IllegalStateException("Stored LEFT event differs from its exact receipt and scope"); + } + return event; + } + + private String leftAuditPayload( + CanonicalScope scope, + MembershipTransitionReceipt receipt, + Event storedEvent, + TransitionReceiptEvidence evidence, + MembershipEvent verifiedEvent) { + LeftAuditPayload payload = + new LeftAuditPayload( + scope.accountUuid().toString(), + scope.tenantUuid().toString(), + receipt.requestId(), + storedEvent.outboxStreamKey(), + Long.toString(storedEvent.outboxSequence()), + storedEvent.eventId(), + storedEvent.eventDigest(), + Map.of(scope.tenantUuid().toString(), Long.toString(evidence.membershipVersion())), + Long.toString(evidence.membershipAuthorityGeneration()), + verifiedEvent == null ? null : verifiedEvent.issuanceFence(), + receipt.receiptStreamKey(), + Long.toString(receipt.receiptSequence()), + receipt.receiptId().toString(), + receipt.receiptDigest()); + try { + return AUDIT_JSON.writeValueAsString(payload); + } catch (Exception exception) { + throw new IllegalStateException( + "Account LEFT audit payload could not be serialized", exception); + } + } + + private void requireExactAuditEnvelope( + CanonicalScope scope, + UUID auditEventId, + long tenantId, + String payload, + AccountAuditEnvelope appended, + AccountAuditEnvelope readback) { + String digest = AccountAuditDigest.ofPayload(payload); + if (scope.legacyTenantId() != tenantId + || !appended.equals(readback) + || !auditEventId.equals(readback.auditEventId()) + || !"tenant".equals(readback.scope()) + || !Long.valueOf(tenantId).equals(readback.tenantId()) + || !"account-service".equals(readback.producerService()) + || !LEFT_AUDIT_TYPE.equals(readback.eventType()) + || readback.schemaVersion() != 1 + || readback.payloadDigestVersion() != 1 + || !digest.equals(readback.payloadDigest()) + || (readback.payload() != null && !payload.equals(readback.payload()))) { + throw new IllegalStateException( + "Account LEFT audit envelope differs from exact operation evidence"); + } + } + + private CanonicalScope resolveCanonicalScope(long accountId, long legacyTenantId) { + Account account = + accountRepository + .findById(accountId) + .orElseThrow(() -> new IllegalStateException("LEFT Account row is absent")); + if (account.getId() == null + || account.getId() != accountId + || account.getAccountUuid() == null + || account.getAccountUuidProvenance() == null + || account.getAccountUuidSourceNumericId() == null + || account.getAccountUuidSourceNumericId() != accountId) { + throw new IllegalStateException( + "LEFT Account UUID does not exactly identify its persisted row"); + } + ApprovedAssociation association = tenantIdentityResolver.resolve(legacyTenantId); + if (association.legacyTenantId() != legacyTenantId + || association.canonicalTenantId() == null + || association.canonicalTenantId().equals(new UUID(0L, 0L))) { + throw new IllegalStateException( + "LEFT retained tenant has no exact approved UUID association"); + } + return new CanonicalScope( + accountId, legacyTenantId, account.getAccountUuid(), association.canonicalTenantId()); + } + + private static String membershipStreamKey(UUID accountUuid, UUID tenantUuid) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountUuid + + "/" + + tenantUuid; + } + + private static UUID leftAuditId(String requestId) { + return UUID.nameUUIDFromBytes( + ("account-membership-left-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); + } + + private static String expectedEventId(String requestId) { + return UUID.nameUUIDFromBytes( + (MembershipAuthorityEventV1Codec.SCHEMA_VERSION + ":" + requestId) + .getBytes(StandardCharsets.UTF_8)) + .toString(); + } + + private static long increment(long value, String field) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Account membership " + field + " is exhausted", overflow); + } + } + + private static void requireRequestId(String requestId) { + if (requestId == null + || requestId.isBlank() + || requestId.length() > 128 + || requestId.indexOf('=') >= 0 + || requestId.indexOf('\n') >= 0 + || requestId.indexOf('\r') >= 0) { + throw new IllegalArgumentException("Stable Account membership request ID is required"); + } + } + + private record CanonicalScope( + long accountId, long legacyTenantId, UUID accountUuid, UUID tenantUuid) {} + + private record LeftAuditPayload( + String accountUuid, + String tenantUuid, + String requestId, + String eventStreamKey, + String eventSequence, + String eventId, + String eventDigest, + Map membershipVersion, + String membershipAuthorityGeneration, + String issuanceFence, + String receiptStreamKey, + String receiptSequence, + String receiptId, + String receiptDigest) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 3a74714a20..57d280b910 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -601,9 +601,11 @@ private static void requireRuntimeMembershipEvidence(RuntimeMembershipSnapshotDt .findFirst() .orElse("0")), new OutboxCheckpointEntry(tenantStreamKey, "0"))); - if (!"ACTIVE".equals(snapshot.membershipBaseline().membershipLifecycleState()) - || !snapshot.gameplayAdmissionAllowed() - || !snapshot.roles().contains("player") + String lifecycleState = snapshot.membershipBaseline().membershipLifecycleState(); + boolean activeMembership = "ACTIVE".equals(lifecycleState); + if ((!activeMembership && !"INACTIVE".equals(lifecycleState)) + || snapshot.gameplayAdmissionAllowed() != activeMembership + || (activeMembership && !snapshot.roles().contains("player")) || !snapshot.outboxCheckpoints().equals(expectedPositiveCheckpoints) || snapshot.outboxSourceEvidence().size() != 1) { throw new IllegalArgumentException("Positive runtime membership snapshot is incomplete"); diff --git a/services/account-service/src/main/resources/db/migration/V40__account_membership_left_transition_receipts.sql b/services/account-service/src/main/resources/db/migration/V40__account_membership_left_transition_receipts.sql new file mode 100644 index 0000000000..cdbfbd4bf6 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V40__account_membership_left_transition_receipts.sql @@ -0,0 +1,28 @@ +ALTER TABLE account_membership_transition_receipts + DROP CONSTRAINT account_membership_transition_receipts_transition_check; + +ALTER TABLE account_membership_transition_receipts + DROP CONSTRAINT account_membership_transition_receipts_state_check; + +ALTER TABLE account_membership_transition_receipts + ADD CONSTRAINT account_membership_transition_receipts_transition_check + CHECK (transition_type IN ( + 'MEMBERSHIP_JOINED', + 'MEMBERSHIP_REACTIVATED', + 'MEMBERSHIP_LEFT' + )); + +ALTER TABLE account_membership_transition_receipts + ADD CONSTRAINT account_membership_transition_receipts_state_check + CHECK ( + authority_provenance = 'EXPLICIT_JOIN' + AND ( + (transition_type IN ('MEMBERSHIP_JOINED', 'MEMBERSHIP_REACTIVATED') + AND membership_lifecycle_state = 'ACTIVE' + AND gameplay_admission_allowed = TRUE) + OR + (transition_type = 'MEMBERSHIP_LEFT' + AND membership_lifecycle_state = 'INACTIVE' + AND gameplay_admission_allowed = FALSE) + ) + ); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java index 906d30f94b..2d6663e325 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -5,7 +5,9 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; @@ -35,6 +37,7 @@ import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; @@ -43,6 +46,7 @@ import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountMembershipLifecycleService; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -108,7 +112,9 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private DSLContext dsl; @Autowired private AccountService accountService; @Autowired private AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer; + @Autowired private AccountMembershipLifecycleService membershipLifecycleService; @Autowired private AccountAuthorityOutboxRepository authorityOutboxRepository; + @MockitoSpyBean private AccountAuditOutboxRepository auditOutboxRepository; @Autowired private PlatformTransactionManager transactionManager; @Autowired @@ -318,6 +324,451 @@ void exactJoinRetryDoesNotAppendAnotherMembershipTransitionReceipt() { assertAuthorityMembershipEvent(fixture, 1L, 2L, false); } + @Test + void leftCommitsClosedAuthorityAndRetainedInactiveRuntimeSnapshot() { + JoinFixture fixture = fixture("active"); + JoinPublicProductionResult joined = join(fixture); + assertThat(joined.success()).isTrue(); + long fenceBeforeLeft = accountIssuanceFence(fixture); + String leftRequestId = "leave-proof-" + UUID.randomUUID(); + + MembershipTransitionReceipt left = leave(fixture, leftRequestId); + + assertThat(left.transitionType()).isEqualTo("MEMBERSHIP_LEFT"); + assertThat(left.requestId()).isEqualTo(leftRequestId); + assertThat(left.receiptSequence()).isEqualTo(2L); + assertThat(membershipSnapshot(fixture)) + .containsEntry("lifecycle_state", "INACTIVE") + .containsEntry("gameplay_admission_allowed", false) + .containsEntry("membership_version", 3L) + .containsEntry("membership_authority_generation", 2L) + .containsEntry("authority_provenance", "EXPLICIT_JOIN"); + assertThat(committedRoles(fixture)).containsExactly("player"); + assertRoleSnapshot(fixture, joined.membershipId(), 3L, List.of("player")); + assertThat(accountIssuanceFence(fixture)).isEqualTo(fenceBeforeLeft + 1L); + assertThat(authorityGeneration("MEMBERSHIP", null, fixture.accountUuid(), fixture.tenantUuid())) + .isEqualTo(2L); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(2L); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(2L); + assertMembershipTransitionReceipt(fixture, "MEMBERSHIP_LEFT", 2L); + var pair = membershipPairAuthorityRow(fixture); + assertThat(pair) + .containsEntry("membership_exists", true) + .containsEntry("membership_version", 3L) + .containsEntry("membership_authority_generation", 2L) + .containsEntry("last_event_sequence", 2L) + .containsEntry("last_transition_invalidated", true); + assertLeftAuthorityMembershipEvent(fixture, leftRequestId, 2L, 3L); + + var runtime = readRuntimeMembershipSnapshot(fixture); + assertThat(runtime.membershipExists()).isTrue(); + assertThat(runtime.gameplayAdmissionAllowed()).isFalse(); + assertThat(runtime.membershipBaseline().membershipLifecycleState()).isEqualTo("INACTIVE"); + assertThat(runtime.membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "3")); + assertThat(runtime.sourceEvent()).isNotNull(); + assertThat(runtime.sourceEvent().requestId()).isEqualTo(leftRequestId); + assertThat(runtime.sourceEvent().callerBoundAuthorityInvalidated()).isTrue(); + assertThat(runtime.outboxCheckpoints()) + .containsExactlyElementsOf(expectedMembershipOutboxCheckpoints(fixture, "2")); + assertThatThrownBy(() -> readPositiveMembershipSnapshot(fixture)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("positive active explicit membership"); + + Map membershipBeforeNewLeftId = membershipSnapshot(fixture); + Map pairBeforeNewLeftId = membershipPairAuthorityRow(fixture); + long fenceBeforeNewLeftId = accountIssuanceFence(fixture); + assertThatThrownBy(() -> leave(fixture, "leave-new-id-" + UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("positive active explicit membership"); + assertThat(membershipSnapshot(fixture)).isEqualTo(membershipBeforeNewLeftId); + assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(pairBeforeNewLeftId); + assertThat(accountIssuanceFence(fixture)).isEqualTo(fenceBeforeNewLeftId); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(2L); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(2L); + assertThat(countLeftAuditEvents(fixture)).isEqualTo(1L); + + UUID auditId = leftAuditId(leftRequestId); + var audit = + dsl.resultQuery( + "SELECT event_type, payload, payload_digest FROM account_audit_outbox " + + "WHERE audit_event_id = ? AND tenant_id = ?", + auditId, + fixture.tenantId()) + .fetchOne(); + assertThat(audit).isNotNull(); + assertThat(audit.get("event_type", String.class)).isEqualTo("ACCOUNT_MEMBERSHIP_LEFT"); + String payload = audit.get("payload", String.class); + assertThat(payload) + .contains(fixture.accountUuid().toString()) + .contains(fixture.tenantUuid().toString()) + .contains(leftRequestId) + .contains(runtime.sourceEvent().eventId()) + .contains(runtime.sourceEvent().eventDigest()) + .contains(left.receiptId().toString()) + .contains(left.receiptDigest()); + assertThat(audit.get("payload_digest", String.class)) + .isEqualTo(net.firedevops.firemud.accountservice.dto.AccountAuditDigest.ofPayload(payload)); + } + + @Test + void concurrentExactLeftRetriesAndReplayAfterReactivationDoNotChurnCurrentAuthority() + throws Exception { + JoinFixture fixture = fixture("active"); + JoinPublicProductionResult joined = join(fixture); + String leftRequestId = "leave-retry-" + UUID.randomUUID(); + AtomicReference firstLeftAttempt = new AtomicReference<>(); + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> { + ready.countDown(); + await(start); + return leave(fixture, leftRequestId); + }); + Future second = + executor.submit( + () -> { + ready.countDown(); + await(start); + return leave(fixture, leftRequestId); + }); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + MembershipTransitionReceipt left = first.get(30, TimeUnit.SECONDS); + firstLeftAttempt.set(left); + assertThat(second.get(30, TimeUnit.SECONDS)).isEqualTo(left); + assertThat(left.transitionType()).isEqualTo("MEMBERSHIP_LEFT"); + assertThat(left.requestId()).isEqualTo(leftRequestId); + assertThat(left.receiptSequence()).isEqualTo(2L); + assertThat(left.membershipId()).isEqualTo(joined.membershipId()); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(2L); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(2L); + assertThat(countLeftAuditEvents(fixture)).isEqualTo(1L); + assertThat(leave(fixture, leftRequestId)).isEqualTo(left); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(2L); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(2L); + assertThat(countLeftAuditEvents(fixture)).isEqualTo(1L); + } finally { + executor.shutdownNow(); + } + MembershipTransitionReceipt left = membershipTransitionReceipt(fixture, 2L); + assertThat(left).isEqualTo(firstLeftAttempt.get()); + + JoinFixture reactivation = fixtureForMembership(fixture); + JoinPublicProductionResult reactivated = join(reactivation); + assertThat(reactivated.success()).isTrue(); + assertThat(reactivated.outcomeCode()).isEqualTo("JOINED"); + assertThat(reactivated.membershipId()).isEqualTo(joined.membershipId()); + assertThat(reactivated.membershipVersion()).isEqualTo(4L); + assertThat(reactivated.membershipAuthorityGeneration()).isEqualTo(3L); + Map membershipBeforeHistoricalReplay = membershipSnapshot(fixture); + Map pairBeforeHistoricalReplay = membershipPairAuthorityRow(fixture); + long fenceBeforeHistoricalReplay = accountIssuanceFence(fixture); + long eventCountBeforeHistoricalReplay = countAuthorityMembershipEvents(fixture); + long receiptCountBeforeHistoricalReplay = countMembershipTransitionReceipts(fixture); + long leftAuditCountBeforeHistoricalReplay = countLeftAuditEvents(fixture); + + assertThat(leave(fixture, leftRequestId)).isEqualTo(left); + assertThat(membershipSnapshot(fixture)).isEqualTo(membershipBeforeHistoricalReplay); + assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(pairBeforeHistoricalReplay); + assertThat(accountIssuanceFence(fixture)).isEqualTo(fenceBeforeHistoricalReplay); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(eventCountBeforeHistoricalReplay); + assertThat(countMembershipTransitionReceipts(fixture)) + .isEqualTo(receiptCountBeforeHistoricalReplay); + assertThat(countLeftAuditEvents(fixture)).isEqualTo(leftAuditCountBeforeHistoricalReplay); + assertThat(membershipSnapshot(fixture)) + .containsEntry("lifecycle_state", "ACTIVE") + .containsEntry("membership_version", 4L) + .containsEntry("membership_authority_generation", 3L); + } + + @Test + void committedLeftWithLostAcknowledgementReadsBackExactReceiptWithoutChurn() { + JoinFixture fixture = fixture("active"); + JoinPublicProductionResult joined = join(fixture); + assertThat(joined.success()).isTrue(); + String leftRequestId = "leave-lost-ack-" + UUID.randomUUID(); + long fenceBeforeLeft = accountIssuanceFence(fixture); + AtomicBoolean loseNextLeftAcknowledgement = new AtomicBoolean(true); + doAnswer( + invocation -> { + Object envelope = invocation.callRealMethod(); + if ("ACCOUNT_MEMBERSHIP_LEFT".equals(invocation.getArgument(3)) + && loseNextLeftAcknowledgement.compareAndSet(true, false)) { + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void afterCommit() { + throw new IllegalStateException( + "simulated lost Account LEFT commit acknowledgement"); + } + }); + } + return envelope; + }) + .when(auditOutboxRepository) + .append( + any(UUID.class), + eq("tenant"), + eq(Long.valueOf(fixture.tenantId())), + eq("ACCOUNT_MEMBERSHIP_LEFT"), + anyString()); + + assertThatThrownBy(() -> leave(fixture, leftRequestId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulated lost Account LEFT commit acknowledgement"); + assertThat(loseNextLeftAcknowledgement.get()).isFalse(); + + MembershipTransitionReceipt committedReceipt = membershipTransitionReceipt(fixture, 2L); + assertThat(committedReceipt.transitionType()).isEqualTo("MEMBERSHIP_LEFT"); + assertThat(committedReceipt.requestId()).isEqualTo(leftRequestId); + assertThat(committedReceipt.membershipId()).isEqualTo(joined.membershipId()); + assertThat(membershipSnapshot(fixture)) + .containsEntry("lifecycle_state", "INACTIVE") + .containsEntry("gameplay_admission_allowed", false) + .containsEntry("membership_version", 3L) + .containsEntry("membership_authority_generation", 2L); + assertThat(membershipPairAuthorityRow(fixture)) + .containsEntry("membership_exists", true) + .containsEntry("membership_version", 3L) + .containsEntry("membership_authority_generation", 2L) + .containsEntry("last_event_sequence", 2L) + .containsEntry("last_transition_invalidated", true); + assertThat(accountIssuanceFence(fixture)).isEqualTo(fenceBeforeLeft + 1L); + assertThat(authorityGeneration("MEMBERSHIP", null, fixture.accountUuid(), fixture.tenantUuid())) + .isEqualTo(2L); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(2L); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(2L); + assertThat(countLeftAuditEvents(fixture)).isEqualTo(1L); + assertLeftAuthorityMembershipEvent(fixture, leftRequestId, 2L, 3L); + + Map membershipAfterCommit = membershipSnapshot(fixture); + Map pairAfterCommit = membershipPairAuthorityRow(fixture); + Map rolesAfterCommit = roleSnapshotRowSnapshot(fixture); + Map firstReceiptAfterCommit = + membershipTransitionReceiptRowSnapshot(fixture, 1L); + Map leftReceiptAfterCommit = + membershipTransitionReceiptRowSnapshot(fixture, 2L); + Map firstEventAfterCommit = authorityMembershipEventSnapshot(fixture, 1L); + Map leftEventAfterCommit = authorityMembershipEventSnapshot(fixture, 2L); + Map leftAuditAfterCommit = leftAuditEnvelopeSnapshot(fixture, leftRequestId); + long generationAfterCommit = + authorityGeneration("MEMBERSHIP", null, fixture.accountUuid(), fixture.tenantUuid()); + long fenceAfterCommit = accountIssuanceFence(fixture); + long authorityOutboxHeadAfterCommit = authorityOutboxHead(fixture); + long receiptHeadAfterCommit = membershipReceiptHead(fixture); + + assertThat(leave(fixture, leftRequestId)).isEqualTo(committedReceipt); + assertThat(membershipSnapshot(fixture)).isEqualTo(membershipAfterCommit); + assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(pairAfterCommit); + assertThat(roleSnapshotRowSnapshot(fixture)).isEqualTo(rolesAfterCommit); + assertThat(membershipTransitionReceiptRowSnapshot(fixture, 1L)) + .isEqualTo(firstReceiptAfterCommit); + assertThat(membershipTransitionReceiptRowSnapshot(fixture, 2L)) + .isEqualTo(leftReceiptAfterCommit); + assertThat(authorityMembershipEventSnapshot(fixture, 1L)).isEqualTo(firstEventAfterCommit); + assertThat(authorityMembershipEventSnapshot(fixture, 2L)).isEqualTo(leftEventAfterCommit); + assertThat(leftAuditEnvelopeSnapshot(fixture, leftRequestId)).isEqualTo(leftAuditAfterCommit); + assertThat(authorityGeneration("MEMBERSHIP", null, fixture.accountUuid(), fixture.tenantUuid())) + .isEqualTo(generationAfterCommit); + assertThat(accountIssuanceFence(fixture)).isEqualTo(fenceAfterCommit); + assertThat(authorityOutboxHead(fixture)).isEqualTo(authorityOutboxHeadAfterCommit); + assertThat(membershipReceiptHead(fixture)).isEqualTo(receiptHeadAfterCommit); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(2L); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(2L); + assertThat(countLeftAuditEvents(fixture)).isEqualTo(1L); + } + + @Test + void reusedLeftAndJoinRequestIdsAreRejectedWithoutCrossScopeMutation() { + JoinFixture leftScope = fixture("active"); + JoinPublicProductionResult originalJoin = join(leftScope); + assertThat(originalJoin.success()).isTrue(); + + JoinFixture otherScope = fixture("active"); + JoinPublicProductionResult otherJoin = join(otherScope); + assertThat(otherJoin.success()).isTrue(); + assertThat(otherScope.accountId()).isNotEqualTo(leftScope.accountId()); + assertThat(otherScope.tenantId()).isNotEqualTo(leftScope.tenantId()); + + String leftRequestId = "leave-cross-scope-" + UUID.randomUUID(); + MembershipTransitionReceipt committedLeft = leave(leftScope, leftRequestId); + assertThat(committedLeft.transitionType()).isEqualTo("MEMBERSHIP_LEFT"); + MembershipScopeSnapshot leftScopeBeforeReuse = + membershipScopeSnapshot(leftScope, leftRequestId); + MembershipScopeSnapshot otherScopeBeforeReuse = membershipScopeSnapshot(otherScope, null); + + assertThatThrownBy(() -> leave(otherScope, leftRequestId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("request ID was reused for another operation"); + assertThat(membershipScopeSnapshot(leftScope, leftRequestId)).isEqualTo(leftScopeBeforeReuse); + assertThat(membershipScopeSnapshot(otherScope, null)).isEqualTo(otherScopeBeforeReuse); + + assertThatThrownBy(() -> leave(leftScope, leftScope.requestId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("request ID was reused for another operation"); + assertThat(membershipScopeSnapshot(leftScope, leftRequestId)).isEqualTo(leftScopeBeforeReuse); + assertThat(membershipScopeSnapshot(otherScope, null)).isEqualTo(otherScopeBeforeReuse); + } + + @Test + void contradictoryLatestEventDeniesLeftWithoutMembershipOrOutboxMutation() { + JoinFixture fixture = fixture("active"); + JoinPublicProductionResult joined = join(fixture); + assertThat(joined.success()).isTrue(); + appendContradictoryCurrentEvent(fixture); + Map membershipBefore = membershipSnapshot(fixture); + Map pairBefore = membershipPairAuthorityRow(fixture); + long fenceBefore = accountIssuanceFence(fixture); + long eventCountBefore = countAuthorityMembershipEvents(fixture); + long receiptCountBefore = countMembershipTransitionReceipts(fixture); + + assertThatThrownBy(() -> leave(fixture, "leave-contradictory-" + UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("receipt differs from its latest V33 event"); + + assertThat(membershipSnapshot(fixture)).isEqualTo(membershipBefore); + assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(pairBefore); + assertThat(accountIssuanceFence(fixture)).isEqualTo(fenceBefore); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(eventCountBefore); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(receiptCountBefore); + assertThat(countLeftAuditEvents(fixture)).isZero(); + } + + @Test + void auditFailureRollsBackCompleteOwnerLeftTransaction() { + JoinFixture fixture = fixture("active"); + JoinPublicProductionResult joined = join(fixture); + assertThat(joined.success()).isTrue(); + Map membershipBefore = membershipSnapshot(fixture); + Map pairBefore = membershipPairAuthorityRow(fixture); + Map rolesBefore = roleSnapshotRowSnapshot(fixture); + Map receiptBefore = membershipTransitionReceiptRowSnapshot(fixture, 1L); + Map eventBefore = authorityMembershipEventSnapshot(fixture, 1L); + long generationBefore = + authorityGeneration("MEMBERSHIP", null, fixture.accountUuid(), fixture.tenantUuid()); + long fenceBefore = accountIssuanceFence(fixture); + long authorityOutboxHeadBefore = authorityOutboxHead(fixture); + long receiptHeadBefore = membershipReceiptHead(fixture); + + doThrow(new IllegalStateException("LEFT audit insert unavailable")) + .when(auditOutboxRepository) + .append( + any(UUID.class), + eq("tenant"), + eq(Long.valueOf(fixture.tenantId())), + eq("ACCOUNT_MEMBERSHIP_LEFT"), + anyString()); + + assertThatThrownBy(() -> leave(fixture, "leave-audit-failure-" + UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("LEFT audit insert unavailable"); + + assertThat(membershipSnapshot(fixture)).isEqualTo(membershipBefore); + assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(pairBefore); + assertThat(roleSnapshotRowSnapshot(fixture)).isEqualTo(rolesBefore); + assertThat(membershipTransitionReceiptRowSnapshot(fixture, 1L)).isEqualTo(receiptBefore); + assertThat(authorityMembershipEventSnapshot(fixture, 1L)).isEqualTo(eventBefore); + assertThat(authorityGeneration("MEMBERSHIP", null, fixture.accountUuid(), fixture.tenantUuid())) + .isEqualTo(generationBefore); + assertThat(accountIssuanceFence(fixture)).isEqualTo(fenceBefore); + assertThat( + dsl.resultQuery( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + authorityStreamKey(fixture)) + .fetchOne(0, Long.class)) + .isEqualTo(authorityOutboxHeadBefore); + assertThat( + dsl.resultQuery( + "SELECT last_receipt_sequence FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)) + .isEqualTo(receiptHeadBefore); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(1L); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(1L); + assertThat(countLeftAuditEvents(fixture)).isZero(); + } + + @Test + void concurrentLeftAndReactivationSerializeAsCompleteAccountTransitions() throws Exception { + JoinFixture fixture = fixture("active"); + assertThat(join(fixture).success()).isTrue(); + JoinFixture reactivation = fixtureForMembership(fixture); + String leftRequestId = "leave-race-" + UUID.randomUUID(); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future leftAttempt = + executor.submit( + () -> { + await(start); + return leave(fixture, leftRequestId); + }); + Future reactivationAttempt = + executor.submit( + () -> { + await(start); + return join(reactivation); + }); + start.countDown(); + + MembershipTransitionReceipt left = leftAttempt.get(30, TimeUnit.SECONDS); + JoinPublicProductionResult joined = reactivationAttempt.get(30, TimeUnit.SECONDS); + assertThat(left.transitionType()).isEqualTo("MEMBERSHIP_LEFT"); + assertThat(joined.success()).isTrue(); + assertThat(joined.outcomeCode()).isIn("JOINED", "ALREADY_ACTIVE"); + assertThat(joined.membershipId()).isEqualTo(left.membershipId()); + + Map currentMembership = membershipSnapshot(fixture); + Map currentPair = membershipPairAuthorityRow(fixture); + if ("JOINED".equals(joined.outcomeCode())) { + assertThat(currentMembership) + .containsEntry("lifecycle_state", "ACTIVE") + .containsEntry("gameplay_admission_allowed", true) + .containsEntry("membership_version", 4L) + .containsEntry("membership_authority_generation", 3L); + assertThat(currentPair) + .containsEntry("membership_version", 4L) + .containsEntry("membership_authority_generation", 3L) + .containsEntry("last_event_sequence", 3L) + .containsEntry("last_transition_invalidated", true); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(3L); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(3L); + } else { + assertThat(currentMembership) + .containsEntry("lifecycle_state", "INACTIVE") + .containsEntry("gameplay_admission_allowed", false) + .containsEntry("membership_version", 3L) + .containsEntry("membership_authority_generation", 2L); + assertThat(currentPair) + .containsEntry("membership_version", 3L) + .containsEntry("membership_authority_generation", 2L) + .containsEntry("last_event_sequence", 2L) + .containsEntry("last_transition_invalidated", true); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(2L); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(2L); + } + assertThat(currentPair.get("last_event_sequence")) + .isEqualTo((long) countAuthorityMembershipEvents(fixture)); + assertThat(countLeftAuditEvents(fixture)).isEqualTo(1L); + var runtime = readRuntimeMembershipSnapshot(fixture); + assertThat(runtime.membershipBaseline().membershipLifecycleState()) + .isEqualTo(currentMembership.get("lifecycle_state")); + assertThat(runtime.gameplayAdmissionAllowed()) + .isEqualTo(currentMembership.get("gameplay_admission_allowed")); + } finally { + executor.shutdownNow(); + } + } + @Test void concurrentDistinctJoinRequestsSerializeOneTransitionAndReplayWithoutMutation() throws Exception { @@ -1530,7 +1981,7 @@ void runtimeMembershipSnapshotRejectsInactiveMembershipWithoutChangingAuthority( assertThatThrownBy(() -> readRuntimeMembershipSnapshot(fixture)) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("not a positive active explicit membership"); + .hasMessageContaining("does not match its latest provisional receipt"); assertThatThrownBy(() -> readExistingPairBoundPositiveMembershipSnapshot(fixture)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not a positive active explicit membership"); @@ -2094,6 +2545,20 @@ private Map membershipSnapshot(JoinFixture fixture) { return row.intoMap(); } + private Map roleSnapshotRowSnapshot(JoinFixture fixture) { + var row = + dsl.resultQuery( + "SELECT s.membership_id, s.snapshot_version " + + "FROM account_tenant_membership_role_snapshots s " + + "JOIN account_tenant_membership m ON m.id = s.membership_id " + + "WHERE m.account_id = ? AND m.tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(); + assertThat(row).isNotNull(); + return Map.of("header", row.intoMap(), "roles", committedRoles(fixture)); + } + private Map membershipTransitionReceiptSnapshot(JoinFixture fixture) { var row = dsl.resultQuery( @@ -2163,6 +2628,100 @@ private JoinPublicProductionResult join(JoinFixture fixture) { new JoinPublicProductionRequest(fixture.connectScopeId(), fixture.requestId())); } + private MembershipTransitionReceipt leave(JoinFixture fixture, String requestId) { + return membershipLifecycleService.leave(fixture.accountId(), fixture.tenantId(), requestId); + } + + private UUID leftAuditId(String requestId) { + return UUID.nameUUIDFromBytes( + ("account-membership-left-audit/v1:" + requestId).getBytes(StandardCharsets.UTF_8)); + } + + private long countLeftAuditEvents(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE scope = 'tenant' " + + "AND tenant_id = ? AND event_type = 'ACCOUNT_MEMBERSHIP_LEFT'", + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private Map leftAuditEnvelopeSnapshot(JoinFixture fixture, String requestId) { + var row = + dsl.resultQuery( + "SELECT audit_event_id, scope, tenant_id, producer_service, event_type, " + + "occurred_at, schema_version, payload_digest_version, payload_digest, payload " + + "FROM account_audit_outbox WHERE audit_event_id = ? AND tenant_id = ?", + leftAuditId(requestId), + fixture.tenantId()) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + + private MembershipScopeSnapshot membershipScopeSnapshot( + JoinFixture fixture, String leftRequestId) { + List> auditEnvelopes = + leftRequestId == null + ? List.of(joinAuditEnvelopeSnapshot(fixture)) + : List.of( + joinAuditEnvelopeSnapshot(fixture), + leftAuditEnvelopeSnapshot(fixture, leftRequestId)); + return new MembershipScopeSnapshot( + membershipSnapshot(fixture), + membershipPairAuthorityRow(fixture), + roleSnapshotRowSnapshot(fixture), + membershipTransitionReceiptRows(fixture), + authorityMembershipEventSnapshots(fixture), + auditEnvelopes, + joinOperationSnapshot(fixture), + authorityGeneration("MEMBERSHIP", null, fixture.accountUuid(), fixture.tenantUuid()), + accountIssuanceFence(fixture), + authorityOutboxHead(fixture), + membershipReceiptHead(fixture), + countMembershipTransitionReceipts(fixture), + countAuthorityMembershipEvents(fixture), + countLeftAuditEvents(fixture)); + } + + private List> membershipTransitionReceiptRows(JoinFixture fixture) { + return dsl + .resultQuery( + "SELECT receipt_stream_key, receipt_sequence, account_id, tenant_id, evidence_status, " + + "transition_type, request_id, membership_id, membership_lifecycle_state, " + + "gameplay_admission_allowed, membership_version, membership_authority_generation, " + + "authority_provenance, receipt_id, receipt_digest, created_at " + + "FROM account_membership_transition_receipts " + + "WHERE account_id = ? AND tenant_id = ? ORDER BY receipt_sequence", + fixture.accountId(), + fixture.tenantId()) + .fetch() + .stream() + .map(row -> row.intoMap()) + .toList(); + } + + private List> authorityMembershipEventSnapshots(JoinFixture fixture) { + return dsl + .resultQuery( + "SELECT outbox_sequence, request_id, event_id, event_digest, payload " + + "FROM account_authority_outbox_events WHERE outbox_stream_key = ? " + + "ORDER BY outbox_sequence", + authorityStreamKey(fixture)) + .fetch() + .stream() + .map( + row -> + Map.of( + "outbox_sequence", row.get("outbox_sequence", Long.class), + "request_id", row.get("request_id", String.class), + "event_id", row.get("event_id", String.class), + "event_digest", row.get("event_digest", String.class), + "payload", + new String(row.get("payload", byte[].class), StandardCharsets.UTF_8))) + .toList(); + } + private void assertAuthorityMembershipEvent( JoinFixture fixture, long expectedSequence, @@ -2257,6 +2816,39 @@ private void assertAuthorityMembershipEvent( Optional.empty())); } + private void assertLeftAuthorityMembershipEvent( + JoinFixture fixture, + String expectedRequestId, + long expectedSequence, + long expectedMembershipVersion) { + var row = authorityMembershipEventRow(fixture, expectedSequence); + assertThat(row).isNotNull(); + byte[] storedPayload = row.get("payload", byte[].class); + String payloadJson = new String(storedPayload, StandardCharsets.UTF_8); + MembershipAuthorityEventV1Codec.MembershipEvent event = + MembershipAuthorityEventV1Codec.verify(payloadJson); + assertThat(row.get("outbox_sequence", Long.class)).isEqualTo(expectedSequence); + assertThat(row.get("request_id", String.class)).isEqualTo(expectedRequestId); + assertThat(row.get("event_id", String.class)).isEqualTo(event.eventId()); + assertThat(row.get("event_digest", String.class)).isEqualTo(event.eventDigest()); + assertThat(event.accountId()).isEqualTo(fixture.accountUuid().toString()); + assertThat(event.tenantId()).isEqualTo(fixture.tenantUuid().toString()); + assertThat(event.outboxStreamKey()).isEqualTo(authorityStreamKey(fixture)); + assertThat(event.outboxSequence()).isEqualTo(Long.toString(expectedSequence)); + assertThat(event.canonicalJson()).contains("\"membershipExists\":true"); + assertThat(event.membershipLifecycleState()).isEqualTo("INACTIVE"); + assertThat(event.membershipVersion()) + .isEqualTo( + Map.of(fixture.tenantUuid().toString(), Long.toString(expectedMembershipVersion))); + assertThat(event.membershipAuthorityGeneration()).isEqualTo("2"); + assertThat(event.roles()).containsExactlyElementsOf(committedRoles(fixture)); + assertThat(event.gameplayAdmissionAllowed()).isFalse(); + assertThat(event.callerBoundAuthorityInvalidated()).isTrue(); + assertThat(event.canonicalJson()).isEqualTo(payloadJson); + assertThat(storedPayload).containsExactly(event.canonicalJsonUtf8()); + assertThat(event.issuanceFence()).isEqualTo(Long.toString(accountIssuanceFence(fixture))); + } + private org.jooq.Record authorityMembershipEventRow(JoinFixture fixture, long sequence) { return dsl.resultQuery( "SELECT outbox_sequence, request_id, event_id, event_digest, payload " @@ -2267,6 +2859,72 @@ private org.jooq.Record authorityMembershipEventRow(JoinFixture fixture, long se .fetchOne(); } + private Map authorityMembershipEventSnapshot(JoinFixture fixture, long sequence) { + var row = authorityMembershipEventRow(fixture, sequence); + assertThat(row).isNotNull(); + return Map.of( + "outbox_sequence", row.get("outbox_sequence", Long.class), + "request_id", row.get("request_id", String.class), + "event_id", row.get("event_id", String.class), + "event_digest", row.get("event_digest", String.class), + "payload", new String(row.get("payload", byte[].class), StandardCharsets.UTF_8)); + } + + private void appendContradictoryCurrentEvent(JoinFixture fixture) { + MembershipAuthorityEventV1Codec.MembershipEvent prior = + MembershipAuthorityEventV1Codec.verify( + new String( + authorityMembershipEventRow(fixture, 1L).get("payload", byte[].class), + StandardCharsets.UTF_8)); + String requestId = "contradictory-current-" + UUID.randomUUID(); + String eventId = + UUID.nameUUIDFromBytes( + (MembershipAuthorityEventV1Codec.SCHEMA_VERSION + ":" + requestId) + .getBytes(StandardCharsets.UTF_8)) + .toString(); + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", prior.authorityTuple().issuerAuthGeneration()); + tuple.put("accountAuthorityGeneration", prior.authorityTuple().accountAuthorityGeneration()); + tuple.put("tenantAuthorityGeneration", prior.authorityTuple().tenantAuthorityGeneration()); + tuple.put( + "membershipAuthorityGeneration", prior.authorityTuple().membershipAuthorityGeneration()); + tuple.put("privateRealmGrantVersions", List.of()); + Map eventPreimage = new LinkedHashMap<>(); + eventPreimage.put("schemaVersion", prior.schemaVersion()); + eventPreimage.put("eventType", prior.eventType()); + eventPreimage.put("eventId", eventId); + eventPreimage.put("requestId", requestId); + eventPreimage.put("outboxStreamKey", authorityStreamKey(fixture)); + eventPreimage.put("outboxSequence", "2"); + eventPreimage.put( + "sourceScope", "membership/" + fixture.accountUuid() + "/" + fixture.tenantUuid()); + eventPreimage.put("accountId", fixture.accountUuid().toString()); + eventPreimage.put("tenantId", fixture.tenantUuid().toString()); + eventPreimage.put("membershipExists", true); + eventPreimage.put("membershipLifecycleState", "ACTIVE"); + eventPreimage.put("membershipVersion", prior.membershipVersion()); + eventPreimage.put("membershipAuthorityGeneration", prior.membershipAuthorityGeneration()); + eventPreimage.put("authorityTuple", tuple); + eventPreimage.put("issuanceFence", prior.issuanceFence()); + eventPreimage.put("roles", prior.roles()); + eventPreimage.put("gameplayAdmissionAllowed", true); + eventPreimage.put("callerBoundAuthorityInvalidated", false); + MembershipAuthorityEventV1Codec.MembershipEvent candidate = + MembershipAuthorityEventV1Codec.seal(eventPreimage); + var appended = + new TransactionTemplate(transactionManager) + .execute( + status -> + authorityOutboxRepository.append( + authorityStreamKey(fixture), + requestId, + candidate.eventId(), + candidate.eventDigest(), + candidate.canonicalJsonUtf8())); + assertThat(appended).isNotNull(); + assertThat(appended.outboxSequence()).isEqualTo(2L); + } + private void assertStoredMembershipVersionFailsClosed( JoinFixture fixture, String malformedMembershipVersionJson) { JoinPublicProductionResult joined = join(fixture); @@ -2338,6 +2996,26 @@ private long accountIssuanceFence(JoinFixture fixture) { .fetchOne(0, Long.class)); } + private long authorityOutboxHead(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + authorityStreamKey(fixture)) + .fetchOne(0, Long.class)); + } + + private long membershipReceiptHead(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT last_receipt_sequence " + + "FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + private List committedRoles(JoinFixture fixture) { return dsl.resultQuery( "SELECT roles.role_identifier FROM account_tenant_membership_role_snapshot_roles roles " @@ -2672,6 +3350,30 @@ private Map membershipTransitionReceiptRowSnapshot( return row.intoMap(); } + private MembershipTransitionReceipt membershipTransitionReceipt( + JoinFixture fixture, long sequence) { + var row = + dsl.resultQuery( + "SELECT receipt_stream_key, receipt_sequence, receipt_id, receipt_digest, " + + "evidence_status, transition_type, request_id, membership_id " + + "FROM account_membership_transition_receipts " + + "WHERE account_id = ? AND tenant_id = ? AND receipt_sequence = ?", + fixture.accountId(), + fixture.tenantId(), + sequence) + .fetchOne(); + assertThat(row).isNotNull(); + return new MembershipTransitionReceipt( + row.get("receipt_stream_key", String.class), + row.get("receipt_sequence", Long.class), + row.get("receipt_id", UUID.class), + row.get("receipt_digest", String.class), + row.get("evidence_status", String.class), + row.get("transition_type", String.class), + row.get("request_id", String.class), + row.get("membership_id", Long.class)); + } + private void assertTransitionAndAuditOutboxOnce(JoinFixture fixture, long membershipId) { assertThat(countMemberships(fixture)).isEqualTo(1L); assertThat( @@ -2710,4 +3412,20 @@ private record JoinFixture( String requestId, DirectTextCallerContext caller, String connectScopeId) {} + + private record MembershipScopeSnapshot( + Map membership, + Map pairAuthority, + Map roles, + List> transitionReceipts, + List> authorityEvents, + List> auditEnvelopes, + Map joinOperation, + long membershipGeneration, + long issuanceFence, + long authorityOutboxHead, + long membershipReceiptHead, + long receiptCount, + long eventCount, + long leftAuditCount) {} } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigestTest.java index e37dd11419..e578ce6b29 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigestTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigestTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.dto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.UUID; import org.junit.jupiter.api.Test; @@ -30,4 +31,89 @@ void joinsUseTheNamespacedProvisionalReceiptIdentityAndDigestVector() { "EXPLICIT_JOIN")) .isEqualTo("sha256:2a07588ddf2444d1b4304cf5bd746365640fc30a2474dc3d0dbe0787d7cc494c"); } + + @Test + void reactivationKeepsItsActiveStateDigestVector() { + UUID receiptId = + MembershipTransitionReceiptDigest.receiptIdForRequest("reactivation-request-1"); + + assertThat(receiptId).isEqualTo(UUID.fromString("328628ab-035d-356f-9827-4e450366c2f7")); + assertThat( + MembershipTransitionReceiptDigest.transitionDigest( + MembershipTransitionReceiptDigest.receiptStreamKey(42L, 7L), + 2L, + receiptId, + "MEMBERSHIP_REACTIVATED", + "reactivation-request-1", + 42L, + 7L, + 18L, + "ACTIVE", + true, + 3L, + 2L, + "EXPLICIT_JOIN")) + .isEqualTo("sha256:f7faf6c9bcd7937386ed3e8443f65fc65ddd4226005145cbd9607acecf231236"); + } + + @Test + void leaveUsesTheSameNamespacedProvisionalReceiptPreimage() { + UUID receiptId = MembershipTransitionReceiptDigest.receiptIdForRequest("leave-request-1"); + + assertThat(receiptId).isEqualTo(UUID.fromString("2ce0e16e-2d24-387d-9059-72e57faa3e56")); + assertThat(transitionDigest(receiptId, "MEMBERSHIP_LEFT", "INACTIVE", false, "leave-request-1")) + .isEqualTo("sha256:cd739f1193f72eb08f543cb74c64dcd39d42247d15e42c6bb58b2672e958d029"); + } + + @Test + void digestRejectsMismatchedTransitionStateAndUnknownType() { + UUID receiptId = MembershipTransitionReceiptDigest.receiptIdForRequest("transition-request"); + + assertThatThrownBy( + () -> + transitionDigest( + receiptId, "MEMBERSHIP_LEFT", "ACTIVE", false, "transition-request")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match"); + assertThatThrownBy( + () -> + transitionDigest( + receiptId, "MEMBERSHIP_LEFT", "INACTIVE", true, "transition-request")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match"); + assertThatThrownBy( + () -> + transitionDigest( + receiptId, "MEMBERSHIP_JOINED", "INACTIVE", false, "transition-request")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match"); + assertThatThrownBy( + () -> + transitionDigest( + receiptId, "MEMBERSHIP_REVOKED", "INACTIVE", false, "transition-request")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not a supported membership receipt"); + } + + private static String transitionDigest( + UUID receiptId, + String transitionType, + String lifecycleState, + boolean gameplayAdmissionAllowed, + String requestId) { + return MembershipTransitionReceiptDigest.transitionDigest( + MembershipTransitionReceiptDigest.receiptStreamKey(42L, 7L), + 3L, + receiptId, + transitionType, + requestId, + 42L, + 7L, + 18L, + lifecycleState, + gameplayAdmissionAllowed, + 4L, + 5L, + "EXPLICIT_JOIN"); + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepositoryTest.java new file mode 100644 index 0000000000..201f2d3ec6 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepositoryTest.java @@ -0,0 +1,90 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountMembershipTransitionReceiptRepositoryTest { + @Test + void appendRequiresAnActualAccountTransactionBeforeRepositoryAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountMembershipTransitionReceiptRepository repository = + new AccountMembershipTransitionReceiptRepository(dsl); + boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(false); + + try { + assertThatThrownBy( + () -> + repository.appendTransition( + membership("ACTIVE", true), "MEMBERSHIP_JOINED", "join-request")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + verifyNoInteractions(dsl); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previouslyActive); + } + } + + @Test + void historicalRequestLookupRequiresAnActualAccountTransactionBeforeRepositoryAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountMembershipTransitionReceiptRepository repository = + new AccountMembershipTransitionReceiptRepository(dsl); + boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(false); + + try { + assertThatThrownBy(() -> repository.findByRequestId("leave-request")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + verifyNoInteractions(dsl); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previouslyActive); + } + } + + @Test + void appendRejectsLeftReceiptForActiveMembershipBeforeAdvancingReceiptHead() { + DSLContext dsl = mock(DSLContext.class); + AccountMembershipTransitionReceiptRepository repository = + new AccountMembershipTransitionReceiptRepository(dsl); + boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + try { + assertThatThrownBy( + () -> + repository.appendTransition( + membership("ACTIVE", true), "MEMBERSHIP_LEFT", "leave-request")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("inactive non-admitting state"); + verifyNoInteractions(dsl); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previouslyActive); + } + } + + private static AccountTenantMembership membership( + String lifecycleState, boolean gameplayAdmissionAllowed) { + Account account = new Account(); + account.setId(42L); + + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setId(18L); + membership.setAccount(account); + membership.setTenantId(7L); + membership.setLifecycleState(lifecycleState); + membership.setGameplayAdmissionAllowed(gameplayAdmissionAllowed); + membership.setMembershipVersion(4L); + membership.setMembershipAuthorityGeneration(5L); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + return membership; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java index 2076cdc2b7..2089ad9b83 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java @@ -16,8 +16,68 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; class AccountMembershipAuthorityEventProducerTest { + @Test + void inactiveMembershipSnapshotRequiresOwnerTransactionBeforeRepositoryReads() { + AccountJoinOperationRepository joinOperationRepository = + mock(AccountJoinOperationRepository.class); + AccountMembershipPairAuthorityRepository pairAuthorityRepository = + mock(AccountMembershipPairAuthorityRepository.class); + AccountRepository accountRepository = mock(AccountRepository.class); + AccountTenantIdentityResolver tenantIdentityResolver = + mock(AccountTenantIdentityResolver.class); + FreshTenantIdentityAssociationRepository freshAssociationRepository = + mock(FreshTenantIdentityAssociationRepository.class); + AccountAuthorityGenerationRepository generationRepository = + mock(AccountAuthorityGenerationRepository.class); + AccountAuthorityOutboxRepository outboxRepository = + mock(AccountAuthorityOutboxRepository.class); + AccountMembershipTransitionReceiptRepository receiptRepository = + mock(AccountMembershipTransitionReceiptRepository.class); + AccountTenantMembershipRepository membershipRepository = + mock(AccountTenantMembershipRepository.class); + AccountTenantMembershipRoleSnapshotRepository rolesRepository = + mock(AccountTenantMembershipRoleSnapshotRepository.class); + AccountMembershipAuthorityEventProducer producer = + new AccountMembershipAuthorityEventProducer( + joinOperationRepository, + pairAuthorityRepository, + accountRepository, + tenantIdentityResolver, + freshAssociationRepository, + generationRepository, + outboxRepository, + receiptRepository, + membershipRepository, + rolesRepository); + boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(false); + + try { + assertThatThrownBy(() -> producer.readCurrentPairBoundInactiveMembershipSnapshot(42L, 7L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + assertThatThrownBy(() -> producer.publishLeftMembershipChange(42L, 7L, "leave-request", null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + verifyNoInteractions( + joinOperationRepository, + pairAuthorityRepository, + accountRepository, + tenantIdentityResolver, + freshAssociationRepository, + generationRepository, + outboxRepository, + receiptRepository, + membershipRepository, + rolesRepository); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previouslyActive); + } + } + @Test void freshSnapshotRequiresOwnerTransactionBeforeRepositoryReads() { AccountJoinOperationRepository joinOperationRepository = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipLifecycleServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipLifecycleServiceTest.java new file mode 100644 index 0000000000..37ff0d5946 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipLifecycleServiceTest.java @@ -0,0 +1,197 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; +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.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountMembershipLifecycleService; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; + +class AccountMembershipLifecycleServiceTest { + @Test + void invalidStableRequestIdIsRejectedBeforeTransactionOrOwnerReads() { + AccountJoinOperationRepository joinOperations = mock(AccountJoinOperationRepository.class); + AccountRepository accounts = mock(AccountRepository.class); + AccountTenantIdentityResolver tenantIdentity = mock(AccountTenantIdentityResolver.class); + AccountTenantMembershipRepository memberships = mock(AccountTenantMembershipRepository.class); + AccountTenantMembershipRoleSnapshotRepository roles = + mock(AccountTenantMembershipRoleSnapshotRepository.class); + AccountMembershipTransitionReceiptRepository receipts = + mock(AccountMembershipTransitionReceiptRepository.class); + AccountAuthorityOutboxRepository authorityOutbox = mock(AccountAuthorityOutboxRepository.class); + AccountAuditOutboxRepository auditOutbox = mock(AccountAuditOutboxRepository.class); + AccountMembershipAuthorityEventProducer producer = + mock(AccountMembershipAuthorityEventProducer.class); + PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + AccountMembershipLifecycleService service = + new AccountMembershipLifecycleService( + joinOperations, + accounts, + tenantIdentity, + memberships, + roles, + receipts, + authorityOutbox, + auditOutbox, + producer, + transactions); + + assertThatThrownBy(() -> service.leave(42L, 7L, " ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Stable Account membership request ID"); + assertThatThrownBy(() -> service.leave(42L, 7L, "r".repeat(129))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Stable Account membership request ID"); + + verifyNoInteractions( + joinOperations, + accounts, + tenantIdentity, + memberships, + roles, + receipts, + authorityOutbox, + auditOutbox, + producer, + transactions); + } + + @Test + void membershipVersionOverflowLeavesMembershipAndRoleRepositoriesUnchanged() { + AccountJoinOperationRepository joinOperations = mock(AccountJoinOperationRepository.class); + AccountRepository accounts = mock(AccountRepository.class); + AccountTenantIdentityResolver tenantIdentity = mock(AccountTenantIdentityResolver.class); + AccountTenantMembershipRepository memberships = mock(AccountTenantMembershipRepository.class); + AccountTenantMembershipRoleSnapshotRepository roles = + mock(AccountTenantMembershipRoleSnapshotRepository.class); + AccountMembershipTransitionReceiptRepository receipts = + mock(AccountMembershipTransitionReceiptRepository.class); + AccountAuthorityOutboxRepository authorityOutbox = mock(AccountAuthorityOutboxRepository.class); + AccountAuditOutboxRepository auditOutbox = mock(AccountAuditOutboxRepository.class); + AccountMembershipAuthorityEventProducer producer = + mock(AccountMembershipAuthorityEventProducer.class); + PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + TransactionStatus transactionStatus = mock(TransactionStatus.class); + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenReturn(transactionStatus); + + long accountId = 42L; + long legacyTenantId = 7L; + UUID accountUuid = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID tenantUuid = UUID.fromString("22222222-2222-4222-8222-222222222222"); + String requestId = "leave-overflow"; + Account account = new Account(); + account.setId(accountId); + account.setAccountUuid(accountUuid); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + account.setAccountUuidSourceNumericId(accountId); + when(accounts.findById(accountId)).thenReturn(Optional.of(account)); + when(tenantIdentity.resolve(legacyTenantId)) + .thenReturn( + new ApprovedAssociation( + legacyTenantId, + tenantUuid, + "legacy-tenant", + 100L, + "sha256:" + "a".repeat(64), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "sha256:" + "b".repeat(64), + "signature", + "account-service-test", + "key", + "reviewer", + "approval", + "2026-01-01T00:00:00Z", + 1, + 1)); + when(receipts.findByRequestId(requestId)).thenReturn(Optional.empty()); + when(joinOperations.find(requestId)).thenReturn(Optional.empty()); + when(authorityOutbox.findEvent( + "account:auth-authority:v1:membership/" + accountUuid + "/" + tenantUuid, requestId)) + .thenReturn(Optional.empty()); + when(auditOutbox.findMembershipLeftEnvelopeForUpdate( + any(UUID.class), org.mockito.ArgumentMatchers.eq(legacyTenantId))) + .thenReturn(Optional.empty()); + + AccountMembershipAuthorityEventProducer.PositiveMembershipSnapshot active = + mock(AccountMembershipAuthorityEventProducer.PositiveMembershipSnapshot.class); + when(active.accountId()).thenReturn(accountUuid.toString()); + when(active.tenantId()).thenReturn(tenantUuid.toString()); + when(active.membershipExists()).thenReturn(true); + when(active.membershipLifecycleState()).thenReturn("ACTIVE"); + when(active.gameplayAdmissionAllowed()).thenReturn(true); + when(active.membershipVersion()) + .thenReturn(Map.of(tenantUuid.toString(), Long.toString(Long.MAX_VALUE))); + when(active.membershipAuthorityGeneration()).thenReturn("1"); + when(active.roles()).thenReturn(List.of("player")); + when(producer.readCurrentPairBoundPositiveMembershipSnapshot(accountId, legacyTenantId)) + .thenReturn(active); + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setId(18L); + membership.setAccount(account); + membership.setTenantId(legacyTenantId); + membership.setLifecycleState("ACTIVE"); + membership.setGameplayAdmissionAllowed(true); + membership.setMembershipVersion(Long.MAX_VALUE); + membership.setMembershipAuthorityGeneration(1L); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + when(memberships.findByAccountIdAndTenantId(accountId, legacyTenantId)) + .thenReturn(Optional.of(membership)); + when(roles.findForUpdate(accountId, legacyTenantId, 18L, Long.MAX_VALUE)) + .thenReturn( + Optional.of( + new RoleSnapshot( + accountId, legacyTenantId, 18L, Long.MAX_VALUE, List.of("player")))); + + AccountMembershipLifecycleService service = + new AccountMembershipLifecycleService( + joinOperations, + accounts, + tenantIdentity, + memberships, + roles, + receipts, + authorityOutbox, + auditOutbox, + producer, + transactions); + + assertThatThrownBy(() -> service.leave(accountId, legacyTenantId, requestId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("membership version is exhausted"); + + assertThat(membership.getLifecycleState()).isEqualTo("ACTIVE"); + assertThat(membership.isGameplayAdmissionAllowed()).isTrue(); + assertThat(membership.getMembershipVersion()).isEqualTo(Long.MAX_VALUE); + verify(memberships, never()).saveAndFlush(any(AccountTenantMembership.class)); + verify(roles, never()).replace(any(AccountTenantMembership.class), anyLong(), any()); + verify(transactions).rollback(transactionStatus); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 86f0f63b82..0f20c736d6 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -153,18 +153,37 @@ private static RuntimeMembershipSnapshotDto runtimeMembershipSnapshot( List checkpoints, List sourceEvidence, MembershipEvent sourceEvent) { + String lifecycleState = membershipExists ? "ACTIVE" : "MISSING"; + return runtimeMembershipSnapshot( + requestAccountUuid, + lifecycleState, + membershipExists, + membershipExists ? "2" : "1", + membershipExists ? List.of("player") : List.of(), + checkpoints, + sourceEvidence, + sourceEvent); + } + + private static RuntimeMembershipSnapshotDto runtimeMembershipSnapshot( + String requestAccountUuid, + String lifecycleState, + boolean gameplayAdmissionAllowed, + String membershipVersion, + List roles, + List checkpoints, + List sourceEvidence, + MembershipEvent sourceEvent) { + boolean membershipExists = !"MISSING".equals(lifecycleState); return new RuntimeMembershipSnapshotDto( requestAccountUuid, TENANT_UUID, ACCOUNT_UUID, TENANT_UUID, membershipExists, - membershipExists, - new MembershipBaseline( - membershipExists ? "ACTIVE" : "MISSING", - Map.of(TENANT_UUID, membershipExists ? "2" : "1"), - "1"), - membershipExists ? List.of("player") : List.of(), + gameplayAdmissionAllowed, + new MembershipBaseline(lifecycleState, Map.of(TENANT_UUID, membershipVersion), "1"), + roles, new AuthorityTuple( "1", "1", @@ -1851,6 +1870,199 @@ void encodeRuntimeMembershipCandidateEncodesCompleteActivePositiveSnapshot() { response.getOutboxSourceEvidence(0).getCanonicalEventJson()); } + @Test + void encodeRuntimeMembershipCandidateEncodesInactivePositiveSnapshotWithoutAdmission() { + MembershipEvent inactiveEvent = + runtimeMembershipAuthorityEvent( + Map.of( + "membershipLifecycleState", + "INACTIVE", + "membershipVersion", + Map.of(TENANT_UUID, "3"), + "roles", + List.of("player"), + "gameplayAdmissionAllowed", + false)); + RuntimeMembershipSnapshotDto snapshot = + runtimeMembershipSnapshot( + ACCOUNT_UUID, + "INACTIVE", + false, + "3", + List.of("player"), + runtimeMembershipCheckpoints("1"), + runtimeMembershipSourceEvidence(inactiveEvent), + inactiveEvent); + + GetTenantMembershipForRuntimeResponse response = + AccountGrpcService.encodeRuntimeMembershipCandidate( + validRuntimeMembershipContext(), snapshot); + + assertTrue(response.getMembershipExists()); + assertFalse(response.getGameplayAdmissionAllowed()); + assertEquals("INACTIVE", response.getMembershipLifecycleState()); + assertEquals(List.of("player"), response.getRolesList()); + assertEquals(Map.of(TENANT_UUID, "3"), response.getMembershipVersionMap()); + assertEquals(1, response.getOutboxSourceEvidenceCount()); + assertEquals(inactiveEvent.eventId(), response.getOutboxSourceEvidence(0).getEventId()); + assertEquals(inactiveEvent.eventDigest(), response.getOutboxSourceEvidence(0).getEventDigest()); + assertEquals( + inactiveEvent.canonicalJson(), response.getOutboxSourceEvidence(0).getCanonicalEventJson()); + } + + @Test + void encodeRuntimeMembershipCandidatePreservesInactiveRolesWithoutAdmission() { + MembershipEvent inactiveEvent = + runtimeMembershipAuthorityEvent( + Map.of( + "membershipLifecycleState", + "INACTIVE", + "membershipVersion", + Map.of(TENANT_UUID, "3"), + "roles", + List.of("designer"), + "gameplayAdmissionAllowed", + false)); + RuntimeMembershipSnapshotDto snapshot = + runtimeMembershipSnapshot( + ACCOUNT_UUID, + "INACTIVE", + false, + "3", + List.of("designer"), + runtimeMembershipCheckpoints("1"), + runtimeMembershipSourceEvidence(inactiveEvent), + inactiveEvent); + + GetTenantMembershipForRuntimeResponse response = + AccountGrpcService.encodeRuntimeMembershipCandidate( + validRuntimeMembershipContext(), snapshot); + + assertTrue(response.getMembershipExists()); + assertFalse(response.getGameplayAdmissionAllowed()); + assertEquals("INACTIVE", response.getMembershipLifecycleState()); + assertEquals(List.of("designer"), response.getRolesList()); + } + + @Test + void runtimeMembershipSnapshotRejectsActiveMembershipWithoutPlayerRole() { + MembershipEvent activeEvent = + runtimeMembershipAuthorityEvent(Map.of("roles", List.of("designer"))); + + assertThrows( + IllegalArgumentException.class, + () -> + runtimeMembershipSnapshot( + ACCOUNT_UUID, + "ACTIVE", + true, + "2", + List.of("designer"), + runtimeMembershipCheckpoints("1"), + runtimeMembershipSourceEvidence(activeEvent), + activeEvent)); + } + + @Test + void runtimeMembershipSnapshotRejectsIncompleteOrContradictoryInactiveEvidence() { + MembershipEvent inactiveEvent = + runtimeMembershipAuthorityEvent( + Map.of( + "membershipLifecycleState", + "INACTIVE", + "membershipVersion", + Map.of(TENANT_UUID, "3"), + "roles", + List.of("player"), + "gameplayAdmissionAllowed", + false)); + List inactiveEvidence = runtimeMembershipSourceEvidence(inactiveEvent); + List checkpoints = runtimeMembershipCheckpoints("1"); + List missingMembershipCheckpoint = + checkpoints.stream() + .filter(item -> !item.outboxStreamKey().equals(inactiveEvent.outboxStreamKey())) + .toList(); + + assertThrows( + IllegalArgumentException.class, + () -> + runtimeMembershipSnapshot( + ACCOUNT_UUID, + "INACTIVE", + false, + "3", + List.of("player"), + checkpoints, + List.of(), + null)); + assertThrows( + IllegalArgumentException.class, + () -> + new OutboxSourceEvidence( + inactiveEvent.outboxStreamKey(), + inactiveEvent.outboxSequence(), + inactiveEvent.eventId(), + "", + inactiveEvent.canonicalJson())); + assertThrows( + IllegalArgumentException.class, + () -> + runtimeMembershipSnapshot( + ACCOUNT_UUID, + "INACTIVE", + false, + "3", + List.of("player"), + missingMembershipCheckpoint, + inactiveEvidence, + inactiveEvent)); + assertThrows( + IllegalArgumentException.class, + () -> + runtimeMembershipSnapshot( + ACCOUNT_UUID, + "INACTIVE", + false, + "3", + List.of("player"), + runtimeMembershipCheckpoints("0"), + inactiveEvidence, + inactiveEvent)); + assertThrows( + IllegalArgumentException.class, + () -> + runtimeMembershipSnapshot( + ACCOUNT_UUID, + "INACTIVE", + false, + "3", + List.of("player"), + checkpoints, + runtimeMembershipSourceEvidence( + runtimeMembershipAuthorityEvent( + Map.of( + "membershipVersion", Map.of(TENANT_UUID, "3"), + "roles", List.of("player")))), + inactiveEvent)); + assertThrows( + IllegalArgumentException.class, + () -> + runtimeMembershipSnapshot( + ACCOUNT_UUID, + "INACTIVE", + true, + "3", + List.of("player"), + checkpoints, + inactiveEvidence, + inactiveEvent)); + assertThrows( + IllegalArgumentException.class, + () -> + runtimeMembershipAuthorityEvent( + Map.of("membershipLifecycleState", "INACTIVE", "gameplayAdmissionAllowed", true))); + } + @Test void encodeRuntimeMembershipCandidateEncodesNeverJoinedSequenceZeroSnapshot() { RuntimeMembershipSnapshotDto snapshot = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index fc32dde859..5d6212b61a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -1121,26 +1121,28 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { } @Test - void playNonPublicInactiveMembershipDoesNotUsePublicJoin() { - SessionContext context = previewRealmContext(); + void playNonPublicLeftMembershipRequiresEnrollment() { + SessionContext context = unboundContext(); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + var leftMembership = + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( + 123L, 22L, List.of("designer", "player"))); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) .thenAnswer( invocation -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .echoRequestId( - freshMembership( - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive(123L, 22L, "3")), - invocation.getArgument(0))); + .echoRequestId(leftMembership, invocation.getArgument(0))); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()) .isEqualTo(GameplayStageCommandConstants.NON_PUBLIC_ENROLLMENT_REQUIRED_CODE); assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) .isEqualTo("error.play.non-public-enrollment-required"); + assertThat(result.outputs()).hasSize(1); Mockito.verify(accountClient, never()) .getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -1148,19 +1150,56 @@ void playNonPublicInactiveMembershipDoesNotUsePublicJoin() { Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(entityManagementClient, never()) - .listCharactersByAccount( + Mockito.verifyNoInteractions( + entityManagementClient, + sessionContextService, + gameplayPresenceLifecycleService, + moderationPolicyClient, + scriptEventPublisher); + } + + @Test + void playBoundNonPublicLeftMembershipRequiresEnrollmentAndClearsBinding() { + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + var leftMembership = + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( + 123L, 22L, List.of("designer", "player"))); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId(leftMembership, invocation.getArgument(0))); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.NON_PUBLIC_ENROLLMENT_REQUIRED_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.non-public-enrollment-required"); + assertThat(result.outputs()).hasSize(1); + Mockito.verify(accountClient, never()) + .getRealmAccessGrantForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), - Mockito.any(PlayableStateScope.class)); + Mockito.anyString(), + Mockito.anyString()); + Mockito.verify(gameplayPresenceLifecycleService) + .clearGameplayBinding(context, "non_public_enrollment_required"); Mockito.verify(sessionContextService) .save( Mockito.argThat( saved -> saved.characterId() == 0L + && saved.characterName() == null && saved.gameInstanceId() == 0L && saved.roomInstanceId() == null)); + Mockito.verifyNoInteractions( + entityManagementClient, moderationPolicyClient, scriptEventPublisher); } @Test @@ -1457,20 +1496,85 @@ void nonAdmittingMembershipLifecycleWithAdmissionFlagIsDenied(String lifecycleSt } @Test - void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { + void playLeftMembershipRequiresJoinForPublicProduction() { + SessionContext context = unboundContext(); + var leftMembership = + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( + 123L, 22L, List.of("designer", "player"))); + var leftEvent = + MembershipAuthorityEventV1Codec.verify( + leftMembership.getOutboxSourceEvidence(0).getCanonicalEventJson()); + assertThat(leftMembership.getMembershipExists()).isTrue(); + assertThat(leftMembership.getGameplayAdmissionAllowed()).isFalse(); + assertThat(leftMembership.getMembershipLifecycleState()).isEqualTo("INACTIVE"); + assertThat(leftMembership.getMembershipVersionMap()) + .containsExactly(Map.entry(leftMembership.getTenantId(), "3")); + assertThat(leftMembership.getMembershipAuthorityGeneration()).isEqualTo("2"); + assertThat(leftMembership.getIssuanceFence()).isEqualTo("2"); + assertThat(leftMembership.getRolesList()).containsExactly("designer", "player"); + assertThat(leftMembership.getAuthorityTuple().getMembershipAuthorityGenerationMap()) + .containsExactly(Map.entry(leftMembership.getTenantId(), "2")); + assertThat(leftMembership.getOutboxCheckpointsList()) + .anySatisfy( + checkpoint -> { + assertThat(checkpoint.getOutboxStreamKey()).isEqualTo(leftEvent.outboxStreamKey()); + assertThat(checkpoint.getOutboxSequence()).isEqualTo("2"); + }); + assertThat(leftMembership.getOutboxSourceEvidence(0).getEventId()) + .isEqualTo(leftEvent.eventId()); + assertThat(leftMembership.getOutboxSourceEvidence(0).getEventDigest()) + .isEqualTo(leftEvent.eventDigest()); + assertThat(leftMembership.getOutboxSourceEvidence(0).getCanonicalEventJson()) + .isEqualTo(leftEvent.canonicalJson()); + assertThat(leftEvent.outboxSequence()).isEqualTo("2"); + assertThat(leftEvent.membershipVersion()) + .containsExactly(Map.entry(leftMembership.getTenantId(), "3")); + assertThat(leftEvent.membershipAuthorityGeneration()).isEqualTo("2"); + assertThat(leftEvent.issuanceFence()).isEqualTo("2"); + assertThat(leftEvent.callerBoundAuthorityInvalidated()).isTrue(); + assertThat(leftEvent.roles()).containsExactly("designer", "player"); + assertThat(leftEvent.gameplayAdmissionAllowed()).isFalse(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId(leftMembership, invocation.getArgument(0))); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.join-required"); + assertThat(result.outputs()).hasSize(1); + Mockito.verifyNoInteractions( + entityManagementClient, + sessionContextService, + gameplayPresenceLifecycleService, + moderationPolicyClient, + scriptEventPublisher); + } + + @Test + void playBoundLeftMembershipRequiresJoinAndClearsBindingForPublicProduction() { SessionContext context = new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + var leftMembership = + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( + 123L, 22L, List.of("designer", "player"))); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) .thenAnswer( invocation -> net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .echoRequestId( - freshMembership( - net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures - .inactive(123L, 22L, "4")), - invocation.getArgument(0))); + .echoRequestId(leftMembership, invocation.getArgument(0))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1480,15 +1584,58 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_CODE); assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) .isEqualTo("error.play.join-required"); + assertThat(result.outputs()).hasSize(1); Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "join_required"); - Mockito.verifyNoInteractions(entityManagementClient); Mockito.verify(sessionContextService) .save( Mockito.argThat( saved -> saved.characterId() == 0L + && saved.characterName() == null && saved.gameInstanceId() == 0L && saved.roomInstanceId() == null)); + Mockito.verifyNoInteractions( + entityManagementClient, moderationPolicyClient, scriptEventPublisher); + } + + @ParameterizedTest + @ValueSource( + strings = { + "membership-generation", + "issuance-fence", + "zero-sequence", + "removed-event", + "altered-roles", + "admission-allowed" + }) + void contradictoryLeftEventEvidenceCannotAdmitGameplay(String defect) { + SessionContext context = unboundContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId( + freshMembership(leftMembershipWithDefect(defect)), + invocation.getArgument(0))); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + assertThat(result.outputs()).hasSize(1); + assertThat(result.outputs().get(0).payload()).isInstanceOf(ErrorOutput.class); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.world-access-denied"); + Mockito.verifyNoInteractions( + entityManagementClient, + sessionContextService, + gameplayPresenceLifecycleService, + moderationPolicyClient, + scriptEventPublisher); } @ParameterizedTest @@ -2253,6 +2400,47 @@ private static GetTenantMembershipForRuntimeResponse freshMembership( return response.toBuilder().setEvaluatedAt(Instant.now().toString()).build(); } + private static GetTenantMembershipForRuntimeResponse leftMembershipWithDefect(String defect) { + var response = + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( + 123L, 22L, List.of("designer", "player")); + var builder = response.toBuilder(); + switch (defect) { + case "membership-generation" -> { + String tenantUuid = response.getTenantId(); + builder + .setMembershipAuthorityGeneration("3") + .setMembershipBaseline( + response.getMembershipBaseline().toBuilder().setMembershipAuthorityGeneration("3")) + .setAuthorityTuple( + response.getAuthorityTuple().toBuilder() + .putMembershipAuthorityGeneration(tenantUuid, "3")); + } + case "issuance-fence" -> builder.setIssuanceFence("3"); + case "zero-sequence" -> { + String membershipStream = response.getOutboxSourceEvidence(0).getOutboxStreamKey(); + boolean updated = false; + for (int index = 0; index < response.getOutboxCheckpointsCount(); index++) { + var checkpoint = response.getOutboxCheckpoints(index); + if (checkpoint.getOutboxStreamKey().equals(membershipStream)) { + builder.setOutboxCheckpoints( + index, checkpoint.toBuilder().setOutboxSequence("0").build()); + updated = true; + break; + } + } + if (!updated) { + throw new IllegalStateException("LEFT fixture is missing its membership checkpoint"); + } + } + case "removed-event" -> builder.clearOutboxSourceEvidence(); + case "altered-roles" -> builder.clearRoles().addRoles("player"); + case "admission-allowed" -> builder.setGameplayAdmissionAllowed(true); + default -> throw new IllegalArgumentException("Unknown LEFT evidence defect: " + defect); + } + return builder.build(); + } + private void assertIdentityUnavailableWithoutMutation(PlayCommandHandlingResult result) { assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()) @@ -2311,6 +2499,25 @@ private SessionContext previewRealmContext() { "SHARED"); } + private SessionContext unboundContext() { + return new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 0L, + null, + 0L, + null, + "jwt-token", + null, + 0L, + null, + null, + 0L, + null); + } + private TextCommand previewRealmPlayCommand() { return new TextCommand( TextCommandType.PLAY, diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java index 36b7f5a74d..e566df0f41 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java @@ -35,6 +35,12 @@ public static GetTenantMembershipForRuntimeResponse inactive( return complete(accountId, tenantId, true, "INACTIVE", false, membershipVersion); } + public static GetTenantMembershipForRuntimeResponse left( + long accountId, long tenantId, List retainedRoles) { + return complete( + accountId, tenantId, true, "INACTIVE", false, "3", "2", "2", "2", true, retainedRoles); + } + public static GetTenantMembershipForRuntimeResponse echoRequestId( GetTenantMembershipForRuntimeResponse response, PlayerExecutionContext request) { return response.toBuilder().setRequestId(request.getRequestId()).build(); @@ -83,6 +89,32 @@ private static GetTenantMembershipForRuntimeResponse complete( String lifecycle, boolean admitted, String membershipVersion) { + return complete( + accountId, + tenantId, + exists, + lifecycle, + admitted, + membershipVersion, + "1", + "1", + exists ? "1" : "0", + false, + admitted ? List.of("player") : List.of()); + } + + private static GetTenantMembershipForRuntimeResponse complete( + long accountId, + long tenantId, + boolean exists, + String lifecycle, + boolean admitted, + String membershipVersion, + String membershipAuthorityGeneration, + String issuanceFence, + String outboxSequence, + boolean callerBoundAuthorityInvalidated, + List roles) { String accountUuid = uuid(accountId); String tenantUuid = uuid(tenantId); String membershipStream = STREAM_PREFIX + "membership/" + accountUuid + "/" + tenantUuid; @@ -91,7 +123,7 @@ private static GetTenantMembershipForRuntimeResponse complete( List.of( checkpoint(STREAM_PREFIX + "account/" + accountUuid, "0"), checkpoint(STREAM_PREFIX + "issuer/" + ISSUER, "0"), - checkpoint(membershipStream, exists ? "1" : "0"), + checkpoint(membershipStream, outboxSequence), checkpoint(STREAM_PREFIX + "tenant/" + tenantUuid, "0"))); checkpoints.sort( (first, second) -> first.getOutboxStreamKey().compareTo(second.getOutboxStreamKey())); @@ -100,13 +132,13 @@ private static GetTenantMembershipForRuntimeResponse complete( .setIssuerAuthGeneration("1") .setAccountAuthorityGeneration("1") .putTenantAuthorityGeneration(tenantUuid, "1") - .putMembershipAuthorityGeneration(tenantUuid, "1") + .putMembershipAuthorityGeneration(tenantUuid, membershipAuthorityGeneration) .build(); RuntimeMembershipBaseline baseline = RuntimeMembershipBaseline.newBuilder() .setMembershipLifecycleState(lifecycle) .putMembershipVersion(tenantUuid, membershipVersion) - .setMembershipAuthorityGeneration("1") + .setMembershipAuthorityGeneration(membershipAuthorityGeneration) .build(); GetTenantMembershipForRuntimeResponse.Builder response = GetTenantMembershipForRuntimeResponse.newBuilder() @@ -118,15 +150,13 @@ private static GetTenantMembershipForRuntimeResponse complete( .setMembershipLifecycleState(lifecycle) .setGameplayAdmissionAllowed(admitted) .putMembershipVersion(tenantUuid, membershipVersion) - .setMembershipAuthorityGeneration("1") + .setMembershipAuthorityGeneration(membershipAuthorityGeneration) .setMembershipBaseline(baseline) .setAuthorityTuple(tuple) - .setIssuanceFence("1") + .setIssuanceFence(issuanceFence) .addAllOutboxCheckpoints(checkpoints) .setEvaluatedAt(Instant.now().toString()); - if (admitted) { - response.addRoles("player"); - } + response.addAllRoles(roles); if (exists) { MembershipAuthorityEventV1Codec.MembershipEvent event = MembershipAuthorityEventV1Codec.seal( @@ -136,30 +166,35 @@ private static GetTenantMembershipForRuntimeResponse complete( Map.entry("eventId", EVENT_ID), Map.entry("requestId", "runtime-membership-request"), Map.entry("outboxStreamKey", membershipStream), - Map.entry("outboxSequence", "1"), + Map.entry("outboxSequence", outboxSequence), Map.entry("sourceScope", "membership/" + accountUuid + "/" + tenantUuid), Map.entry("accountId", accountUuid), Map.entry("tenantId", tenantUuid), Map.entry("membershipExists", true), Map.entry("membershipLifecycleState", lifecycle), Map.entry("membershipVersion", Map.of(tenantUuid, membershipVersion)), - Map.entry("membershipAuthorityGeneration", "1"), + Map.entry("membershipAuthorityGeneration", membershipAuthorityGeneration), Map.entry( "authorityTuple", Map.of( - "issuerAuthGeneration", "1", - "accountAuthorityGeneration", "1", - "tenantAuthorityGeneration", Map.of(tenantUuid, "1"), - "membershipAuthorityGeneration", Map.of(tenantUuid, "1"), - "privateRealmGrantVersions", List.of())), - Map.entry("issuanceFence", "1"), - Map.entry("roles", admitted ? List.of("player") : List.of()), + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(tenantUuid, "1"), + "membershipAuthorityGeneration", + Map.of(tenantUuid, membershipAuthorityGeneration), + "privateRealmGrantVersions", + List.of())), + Map.entry("issuanceFence", issuanceFence), + Map.entry("roles", roles), Map.entry("gameplayAdmissionAllowed", admitted), - Map.entry("callerBoundAuthorityInvalidated", false))); + Map.entry("callerBoundAuthorityInvalidated", callerBoundAuthorityInvalidated))); response.addOutboxSourceEvidence( RuntimeOutboxSourceEvidence.newBuilder() .setOutboxStreamKey(membershipStream) - .setOutboxSequence("1") + .setOutboxSequence(outboxSequence) .setEventId(event.eventId()) .setEventDigest(event.eventDigest()) .setCanonicalEventJson(event.canonicalJson())); From 75ae1dd91701ae02905306cfc3416bc9a4580ff3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 22:16:49 +1300 Subject: [PATCH 02/23] Record Account lifecycle successor in the Unit 1B live index --- design/project-management/design-alignment/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index f479db7cb9..2bb12d9108 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -29,7 +29,7 @@ The preserved 5B implementation work was rebuilt into #2826 Schema, the dependen | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | | 1A | Identity, entitlement, and hosted terms | Provisional; earlier broad discovery closed by judgment, required implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | -| 1B | Admission, session continuity, and reconnect | Provisional; required producer/consumer implementation and proof open | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861), [#2873](https://github.com/benhook1013/FireMUD/pull/2873) → [#2876](https://github.com/benhook1013/FireMUD/pull/2876) → [#2880](https://github.com/benhook1013/FireMUD/pull/2880) → [#2915](https://github.com/benhook1013/FireMUD/pull/2915) | Consolidated owner stages: #2880 retains fenced snapshots, one-use LOGIN storage, complete selected-target context and original committed-source proof from #2881/#2911/#2914. #2915 retains fresh tenant creation/association, UUID pair/snapshot and request candidates, historical recovery/fresh-source correlation, and Game Design tenant-source readback from #2917–#2920. Historical component proof remains head-specific; it does not enable a complete exchange. Full Account authority/credential/registry composition, authenticated authored-world source and audited Game Session association, protected ring delivery, durable reconnect, and HTTPS/mail/abuse/browser proof remain open. Membership RPC and new credential paths stay denied; ring mount unpublished. See the [Player Access tracker](../implementation-tracking/player-access-and-session.md) for exact proof and handoffs. | +| 1B | Admission, session continuity, and reconnect | Provisional; required producer/consumer implementation and proof open | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861), [#2873](https://github.com/benhook1013/FireMUD/pull/2873) → [#2876](https://github.com/benhook1013/FireMUD/pull/2876) → [#2880](https://github.com/benhook1013/FireMUD/pull/2880) → [#2915](https://github.com/benhook1013/FireMUD/pull/2915) → [#2923](https://github.com/benhook1013/FireMUD/pull/2923) | Consolidated owner stages: #2880 retains fenced snapshots, one-use LOGIN storage, complete selected-target context and original committed-source proof from #2881/#2911/#2914. #2915 retains fresh tenant creation/association, UUID pair/snapshot and request candidates, historical recovery/fresh-source correlation, and Game Design tenant-source readback from #2917–#2920. #2923 adds the unwired Account LEFT owner transaction, immutable historical retry and current-INACTIVE evidence; its local PostgreSQL cases are unexecuted. Historical component proof remains head-specific; it does not enable a complete exchange. Full Account authority/credential/registry composition, authenticated authored-world source and audited Game Session association, protected ring delivery, durable reconnect, and HTTPS/mail/abuse/browser proof remain open. Membership RPC and new credential paths stay denied; ring mount unpublished. See the [Player Access tracker](../implementation-tracking/player-access-and-session.md) for exact proof and handoffs. | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | | 2A | Tick scheduling and region authority | Queued | — | — | From 32fe02cbb342365863b83252c91e26d39173abc3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 22:40:10 +1300 Subject: [PATCH 03/23] fix(account): return durable audit envelope after append --- .github/workflows/ci.yml | 1 + .../player-access-and-session.md | 2 + .../AccountAuditOutboxRepository.java | 1 + .../AccountJoinPostgresIntegrationTest.java | 41 +++++++++ .../AccountAuditOutboxRepositoryTest.java | 88 +++++++++++++++++++ 5 files changed, 133 insertions(+) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0c25bb4393..2114501c28 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -976,6 +976,7 @@ jobs: --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#concurrentFirstJoinCannotMixWithCompleteFencedRuntimeMembershipSnapshot()' \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#canonicalExistingPairBoundPositiveMembershipSnapshotRepeatsWithoutMutation()' \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#leftCommitsClosedAuthorityAndRetainedInactiveRuntimeSnapshot()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#auditAppendReadsBackExactStoredTimestampAndEnvelope()' \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#concurrentExactLeftRetriesAndReplayAfterReactivationDoNotChurnCurrentAuthority()' \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#committedLeftWithLostAcknowledgementReadsBackExactReceiptWithoutChurn()' \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#reusedLeftAndJoinRequestIdsAreRejectedWithoutCrossScopeMutation()' \ 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 04d510d797..b094819964 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 +Exact prior child `610ea7b7bcf9f959dbffd452848c710b56e9411b` [CI36839822525](https://github.com/benhook1013/FireMUD/actions/runs/36839822525) executed 38 JOIN/LEFT PostgreSQL cases with five failures and zero skips in the HTML report; the strict Account verifier did not run after the failed full check. Five LEFT paths failed exact audit-envelope readback because append returned the in-memory nanosecond timestamp rather than PostgreSQL's stored timestamp. The correction refreshes the persisted audit record before returning the envelope and propagates unavailable readback; the exact LEFT equality, payload digest and transaction guards are unchanged. Unit proof covers refreshed persisted material and missing readback; the expanded 39-case PostgreSQL suite includes mandatory exact stored timestamp/envelope readback. Corrected-candidate database execution remains required. The same prior run passed the strict five-case Game Session intake proof; other aggregate identity-carrier, retained-fixture and shared-tooling failures remain open. Metadata-only check success is not new runtime proof. + The Game Session tenant-source client and authored-world intake consumer, V7 schema, tests and focused PostgreSQL gate are owned by successor [#2923](https://github.com/benhook1013/FireMUD/pull/2923), not the reduced #2915 producer checkpoint. #2915 retains Game Design's persisted creation/source producer, closed proto/shared evidence and vectors, Account fresh/retained source and UUID authority, and recovery components. The nine-file consumer package is preserved unchanged in the child; the cumulative capability and activation limits are unchanged. Earlier #2915 intake execution below refers to the exact historical head where that package lived, not new evidence on either redistributed head. Runtime catalog, membership RPC and credential paths remain denied; the retained Game Session association, live authenticated handoff and complete authority/consumer proof remain open. The owner-local LEFT candidate passed the consolidated Account/Game Session full checks, affected Java formatting, both service JARs, Checkstyle, SpotBugs, JaCoCo, links, Markdown and Flyway sanity (12 sets/124 files): 153 tasks, 21 executed/132 up-to-date. Account's 469 unit cases and Game Session's 1,731 unit cases executed successfully in the preceding same-code gates; unchanged unit tasks were up-to-date in the final gate. Game Session also executed 18 non-PostgreSQL integration cases and one cross-service case; 17 unit, 116 integration and 33 cross-service cases skipped. All 145 Account PostgreSQL cases, including the expanded 38-case JOIN/LEFT suite and seven required LEFT methods, compiled/discovered but skipped without Docker. Actionlint, all 23 CI-scope contracts and diff hygiene passed. Mocked INACTIVE consumer negatives preserve the production lifecycle guard and distinguish unbound denial from cleanup of an existing binding. Exact-candidate PostgreSQL execution, fresh-image startup and authenticated end-to-end producer/consumer proof remain required; no runtime path is enabled. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java index bb40559950..d6f131f52c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java @@ -50,6 +50,7 @@ public AccountAuditEnvelope append( row.setPayload(payload); row.setDeliveryStatus("PENDING"); row.store(); + row.refresh(); return toEnvelope(row); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java index 2d6663e325..b1829cc549 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -29,6 +29,7 @@ import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; @@ -411,6 +412,46 @@ void leftCommitsClosedAuthorityAndRetainedInactiveRuntimeSnapshot() { .isEqualTo(net.firedevops.firemud.accountservice.dto.AccountAuditDigest.ofPayload(payload)); } + @Test + void auditAppendReadsBackExactStoredTimestampAndEnvelope() { + JoinFixture fixture = fixture("active"); + UUID auditEventId = UUID.randomUUID(); + String payload = + "{\"accountUuid\":\"" + + fixture.accountUuid() + + "\",\"tenantUuid\":\"" + + fixture.tenantUuid() + + "\",\"evidence\":\"exact UTF-8 payload\"}"; + + List appendedAndReadBack = + new TransactionTemplate(transactionManager) + .execute( + status -> { + AccountAuditEnvelope appended = + auditOutboxRepository.append( + auditEventId, + "tenant", + fixture.tenantId(), + "ACCOUNT_MEMBERSHIP_LEFT", + payload); + AccountAuditEnvelope durable = + auditOutboxRepository + .findMembershipLeftEnvelopeForUpdate(auditEventId, fixture.tenantId()) + .orElseThrow(); + return List.of(appended, durable); + }); + + assertThat(appendedAndReadBack).hasSize(2); + AccountAuditEnvelope appended = appendedAndReadBack.get(0); + AccountAuditEnvelope durable = appendedAndReadBack.get(1); + assertThat(appended).isEqualTo(durable); + assertThat(appended.payload()).isEqualTo(payload); + assertThat(appended.payloadDigest()) + .isEqualTo(net.firedevops.firemud.accountservice.dto.AccountAuditDigest.ofPayload(payload)); + assertThat(appended.occurredAt().getNano() % 1_000).isZero(); + assertThat(countLeftAuditEvents(fixture)).isEqualTo(1L); + } + @Test void concurrentExactLeftRetriesAndReplayAfterReactivationDoNotChurnCurrentAuthority() throws Exception { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java new file mode 100644 index 0000000000..75e7714659 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java @@ -0,0 +1,88 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.jooq.tables.AccountAuditOutbox.ACCOUNT_AUDIT_OUTBOX; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.jooq.tables.records.AccountAuditOutboxRecord; +import org.jooq.DSLContext; +import org.jooq.exception.NoDataFoundException; +import org.junit.jupiter.api.Test; + +class AccountAuditOutboxRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final AccountAuditOutboxRepository repository = new AccountAuditOutboxRepository(dsl); + + @Test + void appendReturnsRefreshedPersistedEnvelope() { + UUID auditEventId = UUID.randomUUID(); + AccountAuditOutboxRecord row = mock(AccountAuditOutboxRecord.class); + when(dsl.newRecord(ACCOUNT_AUDIT_OUTBOX)).thenReturn(row); + String persistedPayload = "{\"persisted\":\"exact material\"}"; + String persistedDigest = AccountAuditDigest.ofPayload(persistedPayload); + LocalDateTime persistedOccurredAt = LocalDateTime.parse("2026-10-01T12:34:56.123456"); + doAnswer( + invocation -> { + when(row.getAuditEventId()).thenReturn(auditEventId); + when(row.getScope()).thenReturn("tenant"); + when(row.getTenantId()).thenReturn(73L); + when(row.getProducerService()).thenReturn("account-service"); + when(row.getEventType()).thenReturn("ACCOUNT_MEMBERSHIP_LEFT"); + when(row.getOccurredAt()).thenReturn(persistedOccurredAt); + when(row.getSchemaVersion()).thenReturn(1); + when(row.getPayloadDigestVersion()).thenReturn(1); + when(row.getPayloadDigest()).thenReturn(persistedDigest); + when(row.getPayload()).thenReturn(persistedPayload); + return null; + }) + .when(row) + .refresh(); + + AccountAuditEnvelope envelope = + repository.append( + auditEventId, + "tenant", + 73L, + "ACCOUNT_MEMBERSHIP_LEFT", + "{\"requested\":\"in-memory material\"}"); + + assertThat(envelope) + .isEqualTo( + new AccountAuditEnvelope( + auditEventId, + "tenant", + 73L, + "account-service", + "ACCOUNT_MEMBERSHIP_LEFT", + persistedOccurredAt.toInstant(ZoneOffset.UTC), + 1, + 1, + persistedDigest, + persistedPayload)); + assertThat(envelope.payloadDigest()) + .isEqualTo(AccountAuditDigest.ofPayload(envelope.payload())); + } + + @Test + void appendFailsClosedWhenStoredEnvelopeCannotBeReadBack() { + AccountAuditOutboxRecord row = mock(AccountAuditOutboxRecord.class); + when(dsl.newRecord(ACCOUNT_AUDIT_OUTBOX)).thenReturn(row); + doThrow(new NoDataFoundException("Stored audit envelope is missing")).when(row).refresh(); + + assertThatThrownBy( + () -> + repository.append( + UUID.randomUUID(), "tenant", 73L, "ACCOUNT_MEMBERSHIP_LEFT", "{}")) + .isInstanceOf(NoDataFoundException.class) + .hasMessageContaining("Stored audit envelope is missing"); + } +} From 2583d65671bb8f9256b1216e5cbee5fe50c3d9ff Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 23:39:03 +1300 Subject: [PATCH 04/23] feat(unit1b): persist audited Game Session tenant source approvals --- .github/workflows/ci.yml | 15 + .../game-design-service/api-contracts.md | 16 + .../game-session-service/api-contracts.md | 2 + design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 10 +- .../v1/tenant_identity_service.proto | 34 ++ .../GameSessionTenantAssociationEvidence.java | 167 ++++++ ...eSessionTenantAssociationEvidenceTest.java | 408 +++++++++++++ ...sionTenantAssociationManifestVerifier.java | 68 +++ ...ameSessionTenantAssociationRepository.java | 321 ++++++++++ .../impl/TenantIdentityGrpcService.java | 102 ++++ .../src/main/resources/application-prod.yml | 3 + .../src/main/resources/application.yml | 1 + ..._session_tenant_association_operations.sql | 112 ++++ ...tAssociationRepositoryIntegrationTest.java | 567 ++++++++++++++++++ ...TenantAssociationManifestVerifierTest.java | 448 ++++++++++++++ .../GameSessionTenantAssociationGrpcTest.java | 272 +++++++++ .../impl/TenantIdentityGrpcServiceTest.java | 10 +- ...GameDesignRuntimeTenantIdentityClient.java | 142 +++++ ...DesignRuntimeTenantIdentityClientTest.java | 322 ++++++++++ 20 files changed, 3022 insertions(+), 3 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidence.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidenceTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifier.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepository.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V34__game_session_tenant_association_operations.sql create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifierTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2114501c28..ad5d586254 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -939,6 +939,21 @@ jobs: build-scan-terms-of-use-agree: 'yes' cache-read-only: false + - name: Run Game Design retained Game Session association PostgreSQL component proof + if: ${{ matrix.module == 'game-design-service' }} + run: | + ./gradlew :game-design-service:integrationTest \ + --tests integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#appliesAuditedAssociationForFreshAndRetainedGameSources()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#concurrentExactFirstWritersReturnOneImmutableReceipt()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#ownerRollbackLeavesNoClaimAndLostAcknowledgementRetryReadsExactReceipt()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepositoryIntegrationTest#databaseRejectsAssociationUpdatesDeletesTruncatesAndContradictorySourceInsert()' \ + game-design-service + - name: Run Game Session authored-world intake PostgreSQL component proof if: ${{ matrix.module == 'game-session-service' }} run: | diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 2919e1c1e3..30ff4d904b 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -40,6 +40,22 @@ The readback request binds a distinct canonical non-nil read `requestId` to the **Implementation and activation boundary:** The source repository/codec/readback is a prerequisite candidate, not a protected product creator or a live catalog handoff. Normal official-hosted authoring remains subject to the Account-owned commit-bound creator/terms gate below, which cannot be replaced by the source transaction or a caller-supplied authorization flag. No new public creation route or catalog admission is enabled before its producer, receiver, owner authorization and negative proof pass. Retained Game Session tenant keys need a separate audited, Game Design-authenticated association and Game Session's own exact retained-row readback; Account's manifest and numeric/slug similarity cannot establish it. The [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) owns the remaining implementation and proof. +### Audited retained Game Session tenant association + +This is a distinct, one-time retained-data association, not the Account migration manifest or the normal fresh-creation path. Game Design's approved tenant owner must explicitly attest that one retained Game Session tenant key denotes its persisted canonical tenant. Existing source rows on either side, similar selectors or numeric values do not establish that relation. With no such attestation, the association remains absent and denied. Normal new creation and source intake remain automated owner work; this retained-data approval does not introduce a routine creation-time operator step. + +The closed `game-design/game-session-retained-tenant-association/v1` manifest binds, in fixed order: `schemaVersion=1`, canonical non-nil `operationId`, `targetNamespace`, `signerKeyId`, `approvedBy`, `approvalReference`, canonical UTC `signedAt`, positive decimal-string `legacyGameSessionTenantId`, canonical non-nil `canonicalTenantId`, positive decimal-string `sourceGameRowId`, exact `sourceGameTenantKey`, `provenanceKind`, and `gameSessionEvidenceDigest`. The namespace, source key and provenance retain the runtime-tenant identity bounds above. Row-key decimal strings have no sign, whitespace, leading zero or exponent and must fit their owning PostgreSQL positive BIGINT; they are provenance, not public tenant identifiers. `signedAt` is the exact UTC `Instant.toString()` representation, without expiry semantics. Signer key IDs are bounded to 128 UTF-8 bytes, approval actors to 256 and references to 512; these strings must be nonblank valid Unicode without control characters and are not trimmed or case-folded. Approval labels alone are not authorization. + +The signature and digest preimage starts with the exact domain string above, followed by every manifest field in that order, represented as UTF-8 segments with decimal byte-length `:` framing. The version is the segment `1`; UUIDs use canonical lowercase text. SHA-256 is rendered as `sha256:` plus 64 lowercase hexadecimal digits. Only the separate canonical-base64 64-byte Ed25519 signature and derived digest are excluded from this preimage. Game Design verifies the signature against its protected owner-approval public-key allowlist for this distinct manifest class, exact namespace and actual persisted tenant source before committing any association. An Account manifest cannot be reinterpreted as this type. Unknown fields, invalid signature, untrusted signer, missing source, changed provenance or ambiguous association fail without mutation. + +Game Design atomically claims the operation and stores the complete signed evidence with one-to-one namespace-qualified claims on the canonical UUID and retained Game Session key. An exact retry reads back the same immutable evidence; a changed operation, signature, digest or association conflicts without replacing the original. `TenantIdentityService.ResolveLegacyGameSessionTenantAssociation` accepts a separate canonical non-nil read `requestId`, the exact approval `operationId`, canonical tenant UUID and canonical positive decimal Game Session key. Only the exact same-namespace Game Session mTLS peer may read it, before any owner data access. The closed response echoes the read identity and carries the complete immutable manifest, digest and signature. Game Session authenticates Game Design and validates the separate echo, complete manifest, signature shape and recomputed digest before local use. Neither a digest nor a JWT service claim substitutes for workload authentication. Malformed requests fail `INVALID_ARGUMENT`, absent exact evidence fails `NOT_FOUND`, contradictory readback fails `FAILED_PRECONDITION`, and owner storage unavailability fails `UNAVAILABLE` without exposing a partial result. + +The committed Game Design read validates the stored closed manifest, canonical signature shape, digest, exact scope and persisted source. It does not reauthorize the historical approval against a mutable public-key allowlist; signature authorization occurs before the immutable owner commit and again for a submitted exact retry. Read access still requires the concrete Game Session peer. + +The `gameSessionEvidenceDigest` names Game Session's separately captured retained-row evidence. Before first local association commit, Game Session must verify that exact evidence against its own retained catalog/runtime rows under its owner fence, then store and read back the immutable association and source evidence together. Changed, missing, extra or contradictory captured rows deny that first commit. An exact retry returns the original committed association, not a newly inferred mapping; later catalog state changes do not rewrite the original approval. The concrete retained-row snapshot schema and producer/receiver database proof remain required before this path is wired. This receipt establishes tenant identity only, never current membership, entitlement, lifecycle, pointer or gameplay admission. + +**Implementation and activation boundary:** The manifest and verification contract is a prerequisite for the separately tracked owner persistence, authenticated readback and retained-row consumer. No retained mapping, catalog enrollment, public creation route, credential path or membership RPC is enabled by specifying or locally validating it. Live approval custody and materialization, database concurrency/readback, receiver evidence and authenticated negative-call proof remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + ### Fresh tenant creation operation and Account readback This owner-local prerequisite binds a fresh Game Design-issued UUID to a stable creation request and exposes only authenticated readback to Account. It is not a tenant-creation API, product caller, selector-registration path, membership grant, or runtime activation. The internal producer candidate is not a protected product creator; it must not change smoke-seeder behavior or bypass the official-hosted creator gate in [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md). Any official-hosted creator-intent mutation remains subject to that gate and its current missing implementation/proof. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 85f03529b6..15e0761749 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -36,6 +36,8 @@ Game Session consumes the exact authenticated authored-world receipt defined by ### Authored-world source intake and durable readback +The separate [audited retained-tenant association](../game-design-service/api-contracts.md#audited-retained-game-session-tenant-association) uses this same Game Design-authenticated client channel but a distinct closed manifest and read method. The client checks the independent request echo, exact namespace/operation/tenant/key binding, complete evidence, canonical signature shape and recomputed digest. It does not persist a local retained association or prove the captured Game Session rows; that owner-fenced snapshot and durable receiver remain required before catalog use. The source digest and historical approval are never gameplay authorization. + Game Session's source intake binds its own stable non-nil UUID `intakeRequestId` to the complete immutable Game Design source receipt under the exact workload namespace. The intake service obtains that receipt through the authenticated Game Design source client using a separate read-attempt identity and verifies the requested source operation, tenant UUID and world selector. Before delivering response headers or content, the source client also checks the authenticated TLS leaf's single exact `spiffe://firemud/ns//sa/game-design-service` URI; a trusted CA or matching DNS name alone cannot substitute for workload identity. Missing, ambiguous, another-service or cross-namespace peers fail closed. A caller-constructed receipt, digest alone, Account migration manifest or unchecked transport is not a source authorization. Game Design remains the normative source owner; Game Session's stored copy is the exact consumed evidence, not a new authored selector issuer. The owner transaction atomically persists the local non-nil UUID operation, immutable source evidence and tenant selector claim. Within a namespace, one tenant UUID has one `tenantSlug`, one `tenantSlug` has one tenant UUID, and each `(tenantId, worldSlug)` has one exact consumed source. Compatible additional worlds reuse the same tenant source claim; a conflicting tenant/world/source or changed request fails without partial claims. Exact retries return the original local operation and receipt without changing rows. The transient read-attempt ID is an authenticated response echo, not a replacement intake request or persisted registration field. Exact committed readback is non-mutating and checks the complete stored source and selector binding; it cannot allocate missing state or choose another candidate. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index a46edc7d71..ea0a1df76b 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -174,3 +174,8 @@ Entry format: - Context: a final #2917 tracker edit began a paragraph with a PR hash, which Markdown lint interpreted as a malformed heading. The documentation gate exited nonzero, but its redirected log was not inspected before the local commit. - Observation: no push occurred; inspection identified the lint failure and the unvalidated claim was corrected in a follow-up commit. Earlier successful documentation checks did not cover that last edit. - Expected pattern: consume every final gate's exit status and failure log before committing or publishing proof claims; after a status-only edit, validate that exact edited scope rather than inheriting the preceding green result. + +- `2026-10-01`: Pin module-local configuration in configuration contract tests + - Context: the Game Design owner-read test loaded `application.yml` by its generic classpath name, while several modules provide that same resource name. + - Observation: the test saw an empty method allowlist rather than the owning service's configuration. Loading the module's explicit `src/main/resources` files exposed the actual default and production lists; the corrected assertion passed without weakening the required methods. This is local configuration proof, not live workload authentication. + - Expected pattern: use an explicit owner-module resource when proving a service's configuration, and keep runtime classpath precedence and authenticated deployment proof separate. 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 b094819964..43a5f2f06f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,15 +6,21 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Exact prior child `610ea7b7bcf9f959dbffd452848c710b56e9411b` [CI36839822525](https://github.com/benhook1013/FireMUD/actions/runs/36839822525) executed 38 JOIN/LEFT PostgreSQL cases with five failures and zero skips in the HTML report; the strict Account verifier did not run after the failed full check. Five LEFT paths failed exact audit-envelope readback because append returned the in-memory nanosecond timestamp rather than PostgreSQL's stored timestamp. The correction refreshes the persisted audit record before returning the envelope and propagates unavailable readback; the exact LEFT equality, payload digest and transaction guards are unchanged. Unit proof covers refreshed persisted material and missing readback; the expanded 39-case PostgreSQL suite includes mandatory exact stored timestamp/envelope readback. Corrected-candidate database execution remains required. The same prior run passed the strict five-case Game Session intake proof; other aggregate identity-carrier, retained-fixture and shared-tooling failures remain open. Metadata-only check success is not new runtime proof. +2026-10-01 the #2923 candidate adds the distinct Game Design owner-approved retained Game Session tenant association prerequisite: a closed shared manifest and UTF-8-framed digest, purpose-specific Ed25519 approval verification, V34 immutable one-to-one owner storage, and exact Game Session-only readback. The unwired Game Session client validates the complete echoed manifest and exact request scope over its existing verified Game Design channel. Default and production bearer-bypass lists retain the same exact protected owner reads; their handlers still require the concrete same-namespace peer before owner access. This does not install a local Game Session mapping or prove its retained rows. Protected approval custody/import, the owner-fenced retained-row snapshot and receiver commit/readback, fresh-image and live authentication proof, and catalog/admission activation remain open. The canonical source contract is [Game Design's audited retained association](../../architecture/microservices/game-design-service/api-contracts.md#audited-retained-game-session-tenant-association); Game Session's API records only its consumer consequence. + +The new prerequisite passed local shared-core and Game Design/Game Session full checks, formatting, Checkstyle, SpotBugs, JaCoCo and both service JARs. Shared-core 127 and Game Design 313 unit cases executed with zero skips/failures/errors; Game Session executed 1,738 unit cases, 18 non-PostgreSQL integration cases and one cross-service case without failures/errors. Game Session skipped 17 unit, 116 integration and 33 cross-service cases; all 48 Game Design PostgreSQL cases, including the nine new association cases, compiled/discovered but skipped without Docker. The required new PostgreSQL task and strict method/suite verifier precede the longer Game Design check in CI; their presence is not execution evidence. Local fixture accessor/import and module-resource selection defects were corrected before the passing owner gate. No required assertion, UUID guard or lifecycle boundary was weakened. The composed shared-core/Game Design/Game Session check and packaging gate, links/Markdown and Flyway sanity (12 sets/125 files) passed: 167 tasks, 21 executed/146 up-to-date. Test tasks in that final gate were up-to-date from the preceding same-code executions, not new executions. Actionlint, all 23 CI-scope contracts and diff hygiene also passed. Exact corrected-candidate runner execution and live owner/consumer proof remain required. + +Exact prior child `610ea7b7bcf9f959dbffd452848c710b56e9411b` [CI36839822525](https://github.com/benhook1013/FireMUD/actions/runs/36839822525) executed 38 JOIN/LEFT PostgreSQL cases with five failures and zero skips in the HTML report; the strict Account verifier did not run after the failed full check. Five LEFT paths failed exact audit-envelope readback because append returned the in-memory nanosecond timestamp rather than PostgreSQL's stored timestamp. The correction refreshes the persisted audit record before returning the envelope and propagates unavailable readback; the exact LEFT equality, payload digest and transaction guards are unchanged. Unit proof covers refreshed persisted material; the expanded 39-case PostgreSQL suite includes mandatory exact stored timestamp/envelope readback. Run 36844382190 below supersedes the still-open corrected-candidate database question for its exact child head. The same historical run passed the strict five-case Game Session intake proof; other aggregate identity-carrier, retained-fixture and shared-tooling failures remain open. Metadata-only check success is not new runtime proof. The Game Session tenant-source client and authored-world intake consumer, V7 schema, tests and focused PostgreSQL gate are owned by successor [#2923](https://github.com/benhook1013/FireMUD/pull/2923), not the reduced #2915 producer checkpoint. #2915 retains Game Design's persisted creation/source producer, closed proto/shared evidence and vectors, Account fresh/retained source and UUID authority, and recovery components. The nine-file consumer package is preserved unchanged in the child; the cumulative capability and activation limits are unchanged. Earlier #2915 intake execution below refers to the exact historical head where that package lived, not new evidence on either redistributed head. Runtime catalog, membership RPC and credential paths remain denied; the retained Game Session association, live authenticated handoff and complete authority/consumer proof remain open. The owner-local LEFT candidate passed the consolidated Account/Game Session full checks, affected Java formatting, both service JARs, Checkstyle, SpotBugs, JaCoCo, links, Markdown and Flyway sanity (12 sets/124 files): 153 tasks, 21 executed/132 up-to-date. Account's 469 unit cases and Game Session's 1,731 unit cases executed successfully in the preceding same-code gates; unchanged unit tasks were up-to-date in the final gate. Game Session also executed 18 non-PostgreSQL integration cases and one cross-service case; 17 unit, 116 integration and 33 cross-service cases skipped. All 145 Account PostgreSQL cases, including the expanded 38-case JOIN/LEFT suite and seven required LEFT methods, compiled/discovered but skipped without Docker. Actionlint, all 23 CI-scope contracts and diff hygiene passed. Mocked INACTIVE consumer negatives preserve the production lifecycle guard and distinguish unbound denial from cleanup of an existing binding. Exact-candidate PostgreSQL execution, fresh-image startup and authenticated end-to-end producer/consumer proof remain required; no runtime path is enabled. +Exact child head `32fe02cbb342365863b83252c91e26d39173abc3` [CI36844382190](https://github.com/benhook1013/FireMUD/actions/runs/36844382190) completed FAILURE. The strict runner HTML verifier passed Account JOIN/LEFT39/39 with zero skips, failures or errors, including all seven LEFT cases and the new stored-audit readback. Strict exchange9, connect9, source/history18, fresh association6, pair8 and fresh UUID snapshot11 also passed; Game Design creation8/authored-source10 and Game Session intake5 passed strict. The aggregate remained red: Python Ruff10; a dev-demo summary validator reported an unsupported step with a warning; Automation PostgreSQL8/69 failed; Game Design's broader EntityDigest fixture had one duplicate-key failure among39; TCP Proxy cross-service had13 failures among17; and Game Session's broader check was cancelled after17 CommunicationWebSocket failures. These aggregate failures are not attributed as inherited or flaky. This evidence belongs only to committed child head `32fe02c`; the dirty new Game Design/Game Session association manifest/store/read package in this worktree is uncommitted and has no executed database, receiver, or activation proof. No live readiness or runtime activation is established. + Exact parent `642d5d9f58d8e383c8614697f88f085ef3f56b39` [CI36835527324](https://github.com/benhook1013/FireMUD/actions/runs/36835527324) passed the strict five-case Game Session authored-world intake proof with zero skips/failures/errors. Account strict JOIN31, exchange9, issuance9, source/history18, association6, pair8, fresh UUID snapshot11 and generation2/outbox4, plus Game Design creation8/authored-source10, also passed without skips/failures/errors. These are runner-JUnit verifier results, not uploaded raw XML. Aggregate CI failed, with Game Session's broader check cancelled after 18 CommunicationWebSocket failures; Script Pin25 and focused WebSocket16 proof are not credited. This parent execution does not prove the new LEFT candidate or enable catalog, membership or credential paths. -2026-10-01 Account has an unwired owner-local LEFT component candidate in `AccountMembershipLifecycleService` with V40 receipt-state support. It accepts only an already-proved retained ACTIVE membership pair and, in one Account owner transaction, marks the retained row INACTIVE/non-admitting, preserves its role set, advances membership version and authority generation, and records the canonical invalidating authority event, provisional transition receipt, audit envelope, and pair authority. Exact replay verifies the original immutable event/receipt/audit result; after reactivation it remains historical readback, not current authority. The held-back current-INACTIVE reader requires the existing pair, membership and roles plus the exact latest positive LEFT receipt and matching current checkpoint/event/fence; it does not accept sequence zero, enroll a missing pair, or authorize admission. Public caller authentication/route, fresh-UUID positive JOIN and lifecycle, advanced upstream authority, delivery/projection and consumer convergence, runtime RPC enablement, and credential/catalog activation remain open. PostgreSQL cases for LEFT, replay after reactivation, lost acknowledgement, concurrency, contradiction and rollback are present but have not executed on this candidate; local Docker is unavailable, so no PostgreSQL pass is claimed. [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md), [Authentication](../../architecture/system-architecture-authentication.md), [ADR 0030](../../architecture/decisions/adr-0030-risk-based-active-session-revocation.md), and [ADR 0036](../../architecture/decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md) remain the owners of public lifecycle behavior and authority-generation/revocation semantics. +2026-10-01 Account has an unwired owner-local LEFT component candidate in `AccountMembershipLifecycleService` with V40 receipt-state support. It accepts only an already-proved retained ACTIVE membership pair and, in one Account owner transaction, marks the retained row INACTIVE/non-admitting, preserves its role set, advances membership version and authority generation, and records the canonical invalidating authority event, provisional transition receipt, audit envelope, and pair authority. Exact replay verifies the original immutable event/receipt/audit result; after reactivation it remains historical readback, not current authority. The held-back current-INACTIVE reader requires the existing pair, membership and roles plus the exact latest positive LEFT receipt and matching current checkpoint/event/fence; it does not accept sequence zero, enroll a missing pair, or authorize admission. Public caller authentication/route, fresh-UUID positive JOIN and lifecycle, advanced upstream authority, delivery/projection and consumer convergence, runtime RPC enablement, and credential/catalog activation remain open. The PostgreSQL cases for LEFT, replay after reactivation, lost acknowledgement, concurrency, contradiction and rollback skipped in the owner-local run without Docker; exact child-head PostgreSQL execution and strict component results are recorded above. [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md), [Authentication](../../architecture/system-architecture-authentication.md), [ADR 0030](../../architecture/decisions/adr-0030-risk-based-active-session-revocation.md), and [ADR 0036](../../architecture/decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md) remain the owners of public lifecycle behavior and authority-generation/revocation semantics. Bounded diagnosis of exact prior-head [CI 36826897436](https://github.com/benhook1013/FireMUD/actions/runs/36826897436) on `ada803afcf69fd69555f5ecad55275e424d8623e`: the new CommunicationWebSocket cases need `OK PLAY` or, where public membership is missing, `JOIN_REQUIRED` to reach their communication assertions, but the production path fails before those assertions. The run logs lack response text; the static carrier trace shows `LOGIN` retains numeric Account ID, `PLAY` builds a numeric Account/tenant `PlayerExecutionContext`, and production `AccountClient` requires canonical non-nil UUIDs and denies before the Account stub, which `PLAY` reports as `AUTH_UNAVAILABLE`. The test stub's numeric UUID formatter is not production identity authority, and its numeric request echoes conflict with the UUID protocol. This is an open identity-carrier prerequisite and failed proof, not evidence of an inherited/flaky failure or a resolved path: genuine Account identity, Game Design/Game Session tenant association, and UUID carriers are still required. diff --git a/protos/game-design/v1/tenant_identity_service.proto b/protos/game-design/v1/tenant_identity_service.proto index 80226e85d7..ac061b5864 100644 --- a/protos/game-design/v1/tenant_identity_service.proto +++ b/protos/game-design/v1/tenant_identity_service.proto @@ -21,6 +21,40 @@ service TenantIdentityService { // Exact immutable authored-selector source for Game Session; not catalog enrollment. rpc ResolveAuthoredWorldSource(ResolveAuthoredWorldSourceRequest) returns (ResolveAuthoredWorldSourceResponse); + // Exact audited retained Game Session association; never an Account manifest or admission. + rpc ResolveLegacyGameSessionTenantAssociation(ResolveLegacyGameSessionTenantAssociationRequest) + returns (ResolveLegacyGameSessionTenantAssociationResponse); +} + +message ResolveLegacyGameSessionTenantAssociationRequest { + string request_id = 1; + string operation_id = 2; + string canonical_tenant_id = 3; + // Canonical positive decimal BIGINT provenance, not a public tenant identifier. + string legacy_game_session_tenant_id = 4; +} + +message GameSessionTenantAssociationManifestEvidence { + int32 schema_version = 1; + string operation_id = 2; + string target_namespace = 3; + string signer_key_id = 4; + string approved_by = 5; + string approval_reference = 6; + string signed_at = 7; + string legacy_game_session_tenant_id = 8; + string canonical_tenant_id = 9; + string source_game_row_id = 10; + string source_game_tenant_key = 11; + string provenance_kind = 12; + string game_session_evidence_digest = 13; +} + +message ResolveLegacyGameSessionTenantAssociationResponse { + string request_id = 1; + GameSessionTenantAssociationManifestEvidence manifest = 2; + string manifest_digest = 3; + string ed25519_signature = 4; } message ResolveLegacyGameTenantIdentityRequest { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidence.java new file mode 100644 index 0000000000..e18700e8c8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidence.java @@ -0,0 +1,167 @@ +package net.firedevops.firemud.common.tenant; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.format.DateTimeParseException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Immutable, length-framed evidence for an audited retained Game Session tenant association. */ +public record GameSessionTenantAssociationEvidence( + int schemaVersion, + UUID operationId, + String targetNamespace, + String signerKeyId, + String approvedBy, + String approvalReference, + String signedAt, + String legacyGameSessionTenantId, + UUID canonicalTenantId, + String sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + String gameSessionEvidenceDigest) { + private static final String DOMAIN = "game-design/game-session-retained-tenant-association/v1"; + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public GameSessionTenantAssociationEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Unsupported Game Session tenant association evidence schema version"); + } + requireNonNil(operationId, "operationId"); + requireNamespace(targetNamespace); + requireLabel(signerKeyId, 128, "signerKeyId"); + requireLabel(approvedBy, 256, "approvedBy"); + requireLabel(approvalReference, 512, "approvalReference"); + requireCanonicalInstant(signedAt); + requirePositiveBigintText(legacyGameSessionTenantId, "legacyGameSessionTenantId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requirePositiveBigintText(sourceGameRowId, "sourceGameRowId"); + requireSourceGameTenantKey(sourceGameTenantKey); + if (!"NEW_GAME_ROW".equals(provenanceKind) && !"RETAINED_GAME_V30".equals(provenanceKind)) { + throw new IllegalArgumentException("Game Design tenant provenance kind is not recognized"); + } + if (!GameTenantCreationDigest.isDigest(gameSessionEvidenceDigest)) { + throw new IllegalArgumentException( + "gameSessionEvidenceDigest must be a lowercase SHA-256 digest"); + } + } + + /** Returns the exact shared bytes signed by Game Design and hashed by every consumer. */ + public byte[] preimage() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeSegment(output, DOMAIN); + writeSegment(output, Integer.toString(schemaVersion)); + writeSegment(output, operationId.toString()); + writeSegment(output, targetNamespace); + writeSegment(output, signerKeyId); + writeSegment(output, approvedBy); + writeSegment(output, approvalReference); + writeSegment(output, signedAt); + writeSegment(output, legacyGameSessionTenantId); + writeSegment(output, canonicalTenantId.toString()); + writeSegment(output, sourceGameRowId); + writeSegment(output, sourceGameTenantKey); + writeSegment(output, provenanceKind); + writeSegment(output, gameSessionEvidenceDigest); + return output.toByteArray(); + } + + /** SHA-256 of {@link #preimage()}, excluding the signature and this derived digest. */ + public String manifestDigest() { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(preimage()); + return "sha256:" + HexFormat.of().formatHex(digest); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + /** Returns the retained Game Session tenant key as its exact positive PostgreSQL BIGINT value. */ + public long legacyGameSessionTenantIdValue() { + return Long.parseLong(legacyGameSessionTenantId); + } + + /** Returns the Game Design source row key as its exact positive PostgreSQL BIGINT value. */ + public long sourceGameRowIdValue() { + return Long.parseLong(sourceGameRowId); + } + + private static void writeSegment(ByteArrayOutputStream output, String value) { + int byteLength = GameTenantCreationDigest.utf8ByteLength(value); + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + if (encoded.length != byteLength) { + throw new IllegalStateException("UTF-8 segment length changed after validation"); + } + output.writeBytes(Integer.toString(byteLength).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(encoded); + } + + private static void requireNamespace(String value) { + Objects.requireNonNull(value, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(value)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + GameTenantCreationDigest.utf8ByteLength(value); + } + + private static void requireLabel(String value, int maxUtf8Bytes, String label) { + Objects.requireNonNull(value, label); + int byteLength = GameTenantCreationDigest.utf8ByteLength(value); + if (value.isBlank() + || byteLength > maxUtf8Bytes + || value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(label + " is outside the owner evidence bounds"); + } + } + + private static void requireCanonicalInstant(String value) { + Objects.requireNonNull(value, "signedAt"); + try { + if (!Instant.parse(value).toString().equals(value)) { + throw new IllegalArgumentException("signedAt must be canonical UTC Instant text"); + } + } catch (DateTimeParseException exception) { + throw new IllegalArgumentException("signedAt must be canonical UTC Instant text", exception); + } + } + + private static void requirePositiveBigintText(String value, String label) { + Objects.requireNonNull(value, label); + if (value.length() > 19 || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be canonical positive BIGINT text"); + } + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(label + " must be canonical positive BIGINT text"); + } + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + label + " must fit a positive PostgreSQL BIGINT", exception); + } + } + + private static void requireSourceGameTenantKey(String value) { + Objects.requireNonNull(value, "sourceGameTenantKey"); + GameTenantCreationDigest.utf8ByteLength(value); + if (value.isBlank() || value.length() > 72 || value.codePointCount(0, value.length()) > 36) { + throw new IllegalArgumentException("sourceGameTenantKey is outside the owner key bounds"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must not be nil"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidenceTest.java new file mode 100644 index 0000000000..ed12f8f559 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameSessionTenantAssociationEvidenceTest.java @@ -0,0 +1,408 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class GameSessionTenantAssociationEvidenceTest { + private static final UUID OPERATION_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String GAME_SESSION_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void emitsFixedCompleteUtf8FramingAndManifestDigestVector() { + GameSessionTenantAssociationEvidence evidence = evidence(); + + assertThat(new String(evidence.preimage(), java.nio.charset.StandardCharsets.UTF_8)) + .isEqualTo( + "55:game-design/game-session-retained-tenant-association/v1" + + "1:1" + + "36:11111111-1111-4111-8111-111111111111" + + "7:firemud" + + "14:owner-key-2026" + + "10:owner 🧙" + + "17:review café-🐉" + + "20:2026-10-01T00:00:00Z" + + "16:9007199254740993" + + "36:22222222-2222-4222-8222-222222222222" + + "2:42" + + "18:legacy-game-key-42" + + "17:RETAINED_GAME_V30" + + "71:sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + assertThat(evidence.manifestDigest()) + .isEqualTo("sha256:b3aae3297b6b2d645ad9932ccabc4bb3d6617bdfd36a9207c94c351331e627cc"); + } + + @Test + void exposesLargeCanonicalBigintTextsWithoutFloatingPointLoss() { + GameSessionTenantAssociationEvidence aboveExactDoubleInteger = evidence(); + assertThat(aboveExactDoubleInteger.legacyGameSessionTenantIdValue()) + .isEqualTo(9_007_199_254_740_993L); + + GameSessionTenantAssociationEvidence maxBigint = + copyIds(evidence(), Long.toString(Long.MAX_VALUE), Long.toString(Long.MAX_VALUE)); + assertThat(maxBigint.legacyGameSessionTenantIdValue()).isEqualTo(Long.MAX_VALUE); + assertThat(maxBigint.sourceGameRowIdValue()).isEqualTo(Long.MAX_VALUE); + } + + @Test + void changedValidFieldChangesSharedPreimageAndDigest() { + GameSessionTenantAssociationEvidence source = evidence(); + for (GameSessionTenantAssociationEvidence changed : changedFields(source)) { + assertThat(changed.preimage()).isNotEqualTo(source.preimage()); + assertThat(changed.manifestDigest()).isNotEqualTo(source.manifestDigest()); + } + assertThatThrownBy(() -> copyWithSchemaVersion(source, 2)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("schema version"); + } + + @Test + void preservesApprovalTextExactlyAndRequiresCanonicalUtcInstant() { + GameSessionTenantAssociationEvidence spaced = + new GameSessionTenantAssociationEvidence( + 1, + OPERATION_ID, + "firemud", + "owner-key-2026", + " owner ", + " reference ", + "2026-10-01T00:00:00Z", + "41", + TENANT_ID, + "42", + " legacy-game-key ", + "RETAINED_GAME_V30", + GAME_SESSION_DIGEST); + assertThat(spaced.approvedBy()).isEqualTo(" owner "); + assertThat(spaced.approvalReference()).isEqualTo(" reference "); + assertThat(spaced.sourceGameTenantKey()).isEqualTo(" legacy-game-key "); + + assertInvalid(() -> copySignedAt(evidence(), "2026-10-01T00:00:00+00:00")); + assertInvalid(() -> copySignedAt(evidence(), "2026-10-01T00:00:00.000Z")); + assertInvalid(() -> copySignedAt(evidence(), "not-an-instant")); + } + + @Test + void acceptsUtf8ApprovalLimitsAndTheRuntimeTenantSourceKeyBounds() { + GameSessionTenantAssociationEvidence source = evidence(); + GameSessionTenantAssociationEvidence maximumLabels = + copyWithLabels(source, "é".repeat(64), "é".repeat(128), "é".repeat(256)); + GameSessionTenantAssociationEvidence maximumSourceKey = + copyWithSourceKey(source, "🐉".repeat(36)); + + assertThat(maximumLabels.signerKeyId()).hasSize(64); + assertThat(maximumLabels.approvedBy()).hasSize(128); + assertThat(maximumLabels.approvalReference()).hasSize(256); + assertThat(maximumSourceKey.sourceGameTenantKey()).hasSize(72); + } + + @Test + void rejectsMalformedIdentifiersBoundsUnicodeAndClosedEnums() { + GameSessionTenantAssociationEvidence source = evidence(); + assertInvalid(() -> withIds(source, "0", source.sourceGameRowId())); + assertInvalid(() -> withIds(source, "01", source.sourceGameRowId())); + assertInvalid(() -> withIds(source, "+1", source.sourceGameRowId())); + assertInvalid(() -> withIds(source, "9223372036854775808", source.sourceGameRowId())); + assertInvalid(() -> withIds(source, source.legacyGameSessionTenantId(), "00")); + assertInvalid(() -> withIds(source, source.legacyGameSessionTenantId(), "9223372036854775808")); + assertInvalid(() -> copyWithUuid(source, new UUID(0L, 0L), source.canonicalTenantId())); + assertInvalid(() -> copyWithUuid(source, source.operationId(), new UUID(0L, 0L))); + assertInvalid(() -> copyWithNamespace(source, "firemud.invalid")); + assertInvalid(() -> copyWithSourceKey(source, " ")); + assertInvalid(() -> copyWithSourceKey(source, "x".repeat(37))); + assertInvalid(() -> copyWithSourceKey(source, "x" + (char) 0xd800)); + assertInvalid( + () -> + copyWithLabels( + source, "k".repeat(129), source.approvedBy(), source.approvalReference())); + assertInvalid( + () -> + copyWithLabels( + source, source.signerKeyId(), "a".repeat(257), source.approvalReference())); + assertInvalid( + () -> copyWithLabels(source, source.signerKeyId(), source.approvedBy(), "r".repeat(513))); + assertInvalid( + () -> + copyWithLabels( + source, source.signerKeyId(), "owner\nname", source.approvalReference())); + assertInvalid(() -> copyWithProvenance(source, "OTHER")); + assertInvalid(() -> copyWithEvidenceDigest(source, "SHA256:" + "a".repeat(64))); + } + + private static GameSessionTenantAssociationEvidence evidence() { + return new GameSessionTenantAssociationEvidence( + 1, + OPERATION_ID, + "firemud", + "owner-key-2026", + "owner 🧙", + "review café-🐉", + Instant.parse("2026-10-01T00:00:00Z").toString(), + "9007199254740993", + TENANT_ID, + "42", + "legacy-game-key-42", + "RETAINED_GAME_V30", + GAME_SESSION_DIGEST); + } + + private static GameSessionTenantAssociationEvidence copySignedAt( + GameSessionTenantAssociationEvidence source, String signedAt) { + return copy( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + signedAt, + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyIds( + GameSessionTenantAssociationEvidence source, + String legacyGameSessionTenantId, + String sourceGameRowId) { + return copy( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + legacyGameSessionTenantId, + source.canonicalTenantId(), + sourceGameRowId, + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithSchemaVersion( + GameSessionTenantAssociationEvidence source, int schemaVersion) { + return copy( + source, + schemaVersion, + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithNamespace( + GameSessionTenantAssociationEvidence source, String namespace) { + return copy( + source, + source.schemaVersion(), + source.operationId(), + namespace, + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithUuid( + GameSessionTenantAssociationEvidence source, UUID operationId, UUID canonicalTenantId) { + return copy( + source, + source.schemaVersion(), + operationId, + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + canonicalTenantId, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithSourceKey( + GameSessionTenantAssociationEvidence source, String sourceGameTenantKey) { + return copy( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + sourceGameTenantKey, + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithLabels( + GameSessionTenantAssociationEvidence source, + String signerKeyId, + String approvedBy, + String approvalReference) { + return copy( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + signerKeyId, + approvedBy, + approvalReference, + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithProvenance( + GameSessionTenantAssociationEvidence source, String provenanceKind) { + return copy( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + provenanceKind, + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithEvidenceDigest( + GameSessionTenantAssociationEvidence source, String gameSessionEvidenceDigest) { + return copy( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + gameSessionEvidenceDigest); + } + + private static GameSessionTenantAssociationEvidence withIds( + GameSessionTenantAssociationEvidence source, + String legacyGameSessionTenantId, + String sourceGameRowId) { + return copyIds(source, legacyGameSessionTenantId, sourceGameRowId); + } + + private static GameSessionTenantAssociationEvidence copy( + GameSessionTenantAssociationEvidence source, + int schemaVersion, + UUID operationId, + String targetNamespace, + String signerKeyId, + String approvedBy, + String approvalReference, + String signedAt, + String legacyGameSessionTenantId, + UUID canonicalTenantId, + String sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + String gameSessionEvidenceDigest) { + return new GameSessionTenantAssociationEvidence( + schemaVersion, + operationId, + targetNamespace, + signerKeyId, + approvedBy, + approvalReference, + signedAt, + legacyGameSessionTenantId, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + gameSessionEvidenceDigest); + } + + private static void assertInvalid(Runnable construction) { + assertThatThrownBy(construction::run).isInstanceOf(IllegalArgumentException.class); + } + + private static java.util.List changedFields( + GameSessionTenantAssociationEvidence source) { + return java.util.List.of( + copyIds(source, "9007199254740994", source.sourceGameRowId()), + copyWithNamespace(source, "firemud-dev"), + copyWithLabels(source, "owner-key-2027", source.approvedBy(), source.approvalReference()), + copyWithLabels(source, source.signerKeyId(), "another owner", source.approvalReference()), + copyWithLabels( + source, source.signerKeyId(), source.approvedBy(), "another-review-reference"), + copySignedAt(source, "2026-10-01T00:00:01Z"), + copyWithOperationId(source, UUID.fromString("33333333-3333-4333-8333-333333333333")), + copyWithUuid( + source, source.operationId(), UUID.fromString("33333333-3333-4333-8333-333333333333")), + copyIds(source, source.legacyGameSessionTenantId(), "43"), + copyWithSourceKey(source, "another-source-key"), + copyWithProvenance(source, "NEW_GAME_ROW"), + copyWithEvidenceDigest(source, "sha256:" + "b".repeat(64))); + } + + private static GameSessionTenantAssociationEvidence copyWithOperationId( + GameSessionTenantAssociationEvidence source, UUID operationId) { + return copy( + source, + source.schemaVersion(), + operationId, + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifier.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifier.java new file mode 100644 index 0000000000..15d39c0bf2 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifier.java @@ -0,0 +1,68 @@ +package net.firedevops.firemud.gamedesign.maintenance; + +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.Signature; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; +import java.util.Map; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; + +/** Verifies Game Design owner approval for one retained Game Session tenant association. */ +public final class GameSessionTenantAssociationManifestVerifier { + private GameSessionTenantAssociationManifestVerifier() {} + + /** + * Verifies canonical signed evidence with the protected, purpose-specific Game Design owner + * approval public-key allowlist. This map is not an Account key ring or a general JWKS. + */ + public static Verified verify(Signed signed, Map trustedOwnerApprovalPublicKeys) { + if (signed == null || signed.manifest() == null || trustedOwnerApprovalPublicKeys == null) { + throw new IllegalArgumentException("signed Game Session tenant association is required"); + } + GameSessionTenantAssociationEvidence manifest = signed.manifest(); + String encodedKey = trustedOwnerApprovalPublicKeys.get(manifest.signerKeyId()); + if (encodedKey == null || encodedKey.isBlank()) { + throw new IllegalArgumentException("manifest signer is not trusted for owner approval"); + } + + try { + byte[] encodedKeyBytes = Base64.getDecoder().decode(encodedKey); + if (!Base64.getEncoder().encodeToString(encodedKeyBytes).equals(encodedKey)) { + throw new IllegalArgumentException("owner approval public key encoding is not canonical"); + } + PublicKey publicKey = + KeyFactory.getInstance("Ed25519").generatePublic(new X509EncodedKeySpec(encodedKeyBytes)); + byte[] preimage = manifest.preimage(); + byte[] signatureBytes = decodeCanonicalSignature(signed.ed25519Signature()); + Signature verifier = Signature.getInstance("Ed25519"); + verifier.initVerify(publicKey); + verifier.update(preimage); + if (!verifier.verify(signatureBytes)) { + throw new IllegalArgumentException("manifest owner signature is invalid"); + } + return new Verified(manifest, manifest.manifestDigest()); + } catch (IllegalArgumentException exception) { + throw exception; + } catch (Exception exception) { + throw new IllegalArgumentException("manifest owner signature cannot be verified", exception); + } + } + + private static byte[] decodeCanonicalSignature(String encodedSignature) { + if (encodedSignature == null || encodedSignature.isBlank()) { + throw new IllegalArgumentException("manifest owner signature is required"); + } + byte[] signatureBytes = Base64.getDecoder().decode(encodedSignature); + if (signatureBytes.length != 64 + || !Base64.getEncoder().encodeToString(signatureBytes).equals(encodedSignature)) { + throw new IllegalArgumentException( + "manifest owner signature must be canonical 64-byte Ed25519"); + } + return signatureBytes; + } + + public record Signed(GameSessionTenantAssociationEvidence manifest, String ed25519Signature) {} + + public record Verified(GameSessionTenantAssociationEvidence manifest, String manifestDigest) {} +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepository.java new file mode 100644 index 0000000000..85e859dc05 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepository.java @@ -0,0 +1,321 @@ +package net.firedevops.firemud.gamedesign.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Base64; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamedesign.maintenance.GameSessionTenantAssociationManifestVerifier; +import net.firedevops.firemud.gamedesign.maintenance.GameSessionTenantAssociationManifestVerifier.Signed; +import net.firedevops.firemud.gamedesign.maintenance.GameSessionTenantAssociationManifestVerifier.Verified; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Immutable Game Design owner receipt for an audited retained Game Session tenant association. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext and GameRepository are internal owner collaborators.") +public class GameSessionTenantAssociationRepository { + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + + private static final Table ASSOCIATION = + DSL.table(DSL.name("game_design_game_session_tenant_association_operations")); + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field SCHEMA_VERSION = + DSL.field(DSL.name("schema_version"), Integer.class); + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field SIGNER_KEY_ID = + DSL.field(DSL.name("signer_key_id"), String.class); + private static final Field APPROVED_BY = DSL.field(DSL.name("approved_by"), String.class); + private static final Field APPROVAL_REFERENCE = + DSL.field(DSL.name("approval_reference"), String.class); + private static final Field SIGNED_AT = DSL.field(DSL.name("signed_at"), String.class); + private static final Field LEGACY_GAME_SESSION_TENANT_ID = + DSL.field(DSL.name("legacy_game_session_tenant_id"), Long.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field GAME_SESSION_EVIDENCE_DIGEST = + DSL.field(DSL.name("game_session_evidence_digest"), String.class); + private static final Field MANIFEST_DIGEST = + DSL.field(DSL.name("manifest_digest"), String.class); + private static final Field SIGNATURE = DSL.field(DSL.name("signature"), String.class); + + private final DSLContext dsl; + private final GameRepository gameRepository; + + public GameSessionTenantAssociationRepository(DSLContext dsl, GameRepository gameRepository) { + this.dsl = dsl; + this.gameRepository = gameRepository; + } + + /** + * Verifies and atomically records the approved association inside its caller's owner transaction. + * + *

The actual canonical-UUID game row is locked before source validation and the one-row claim. + * A uniqueness conflict is resolved by exact persisted operation readback after the insert + * attempt, so no preflight lookup can race into a false successful claim. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AssociationReceipt apply( + Signed signed, Map trustedPublicKeys, String exactNamespace) { + Verified verified = + GameSessionTenantAssociationManifestVerifier.verify(signed, trustedPublicKeys); + GameSessionTenantAssociationEvidence manifest = verified.manifest(); + if (exactNamespace == null || !exactNamespace.equals(manifest.targetNamespace())) { + throw new IllegalArgumentException("manifest targets a different namespace"); + } + requireActiveOwnerTransaction(); + + GameTenantIdentity source = lockAndReadSource(manifest.canonicalTenantId()); + requireManifestSource(manifest, source); + + int inserted = + dsl.insertInto(ASSOCIATION) + .set(OPERATION_ID, manifest.operationId()) + .set(SCHEMA_VERSION, manifest.schemaVersion()) + .set(TARGET_NAMESPACE, manifest.targetNamespace()) + .set(SIGNER_KEY_ID, manifest.signerKeyId()) + .set(APPROVED_BY, manifest.approvedBy()) + .set(APPROVAL_REFERENCE, manifest.approvalReference()) + .set(SIGNED_AT, manifest.signedAt()) + .set(LEGACY_GAME_SESSION_TENANT_ID, manifest.legacyGameSessionTenantIdValue()) + .set(CANONICAL_TENANT_ID, manifest.canonicalTenantId()) + .set(SOURCE_GAME_ROW_ID, manifest.sourceGameRowIdValue()) + .set(SOURCE_GAME_TENANT_KEY, manifest.sourceGameTenantKey()) + .set(PROVENANCE_KIND, manifest.provenanceKind()) + .set(GAME_SESSION_EVIDENCE_DIGEST, manifest.gameSessionEvidenceDigest()) + .set(MANIFEST_DIGEST, verified.manifestDigest()) + .set(SIGNATURE, signed.ed25519Signature()) + .onConflictDoNothing() + .execute(); + + Record persisted = findByOperationId(manifest.operationId()); + if (persisted == null) { + if (inserted == 0) { + throw new AssociationConflictException( + "canonical tenant or retained Game Session key is already associated"); + } + throw new InvalidAssociationEvidenceException( + "committed Game Session tenant association operation is missing"); + } + + AssociationReceipt receipt = toValidatedReceipt(persisted); + requireExactReceipt(verified, signed.ed25519Signature(), receipt); + requireManifestSource(receipt.manifest(), source); + return receipt; + } + + /** + * Reads exact committed owner evidence without allocation, repair, or signature reauthorization. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read( + UUID operationId, + UUID canonicalTenantId, + long legacyGameSessionTenantId, + String exactNamespace) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Session tenant association read requires a committed-outcome owner read"); + } + if (operationId == null || operationId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("operationId must be a canonical non-nil UUID"); + } + if (canonicalTenantId == null || canonicalTenantId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("canonicalTenantId must be a canonical non-nil UUID"); + } + if (legacyGameSessionTenantId <= 0) { + throw new IllegalArgumentException("legacy Game Session tenant key must be positive"); + } + if (exactNamespace == null || exactNamespace.isBlank()) { + throw new IllegalArgumentException("exact namespace is required"); + } + + Record row = + dsl.selectFrom(ASSOCIATION) + .where( + OPERATION_ID + .eq(operationId) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(LEGACY_GAME_SESSION_TENANT_ID.eq(legacyGameSessionTenantId)) + .and(TARGET_NAMESPACE.eq(exactNamespace))) + .fetchOne(); + if (row == null) { + return Optional.empty(); + } + + AssociationReceipt receipt = toValidatedReceipt(row); + GameTenantIdentity source = + gameRepository + .findRuntimeTenantIdentityByCanonicalTenantId(receipt.manifest().canonicalTenantId()) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "persisted Game Session tenant association source is missing")); + requireManifestSource(receipt.manifest(), source); + return Optional.of(receipt); + } + + private GameTenantIdentity lockAndReadSource(UUID canonicalTenantId) { + Long lockedGameId = + dsl.select(GAME_ID) + .from(GAME) + .where(GAME_CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .forUpdate() + .fetchOne(GAME_ID); + if (lockedGameId == null) { + throw new AssociationConflictException("canonical tenant source game row is missing"); + } + GameTenantIdentity source = + gameRepository + .findRuntimeTenantIdentityByCanonicalTenantId(canonicalTenantId) + .orElseThrow( + () -> + new AssociationConflictException( + "canonical tenant source game row is missing")); + if (source.sourceGameId() == null || !lockedGameId.equals(source.sourceGameId())) { + throw new InvalidAssociationEvidenceException( + "locked Game Design source row changed during canonical tenant readback"); + } + return source; + } + + private Record findByOperationId(UUID operationId) { + return dsl.selectFrom(ASSOCIATION).where(OPERATION_ID.eq(operationId)).fetchOne(); + } + + private AssociationReceipt toValidatedReceipt(Record row) { + try { + GameSessionTenantAssociationEvidence manifest = + new GameSessionTenantAssociationEvidence( + row.get(SCHEMA_VERSION), + row.get(OPERATION_ID), + row.get(TARGET_NAMESPACE), + row.get(SIGNER_KEY_ID), + row.get(APPROVED_BY), + row.get(APPROVAL_REFERENCE), + row.get(SIGNED_AT), + Long.toString(row.get(LEGACY_GAME_SESSION_TENANT_ID)), + row.get(CANONICAL_TENANT_ID), + Long.toString(row.get(SOURCE_GAME_ROW_ID)), + row.get(SOURCE_GAME_TENANT_KEY), + row.get(PROVENANCE_KIND), + row.get(GAME_SESSION_EVIDENCE_DIGEST)); + String signature = row.get(SIGNATURE); + requireCanonicalSignatureShape(signature); + String persistedDigest = row.get(MANIFEST_DIGEST); + if (!manifest.manifestDigest().equals(persistedDigest)) { + throw new InvalidAssociationEvidenceException( + "persisted Game Session tenant association digest does not match its manifest"); + } + return new AssociationReceipt(manifest, signature, persistedDigest); + } catch (InvalidAssociationEvidenceException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidAssociationEvidenceException( + "persisted Game Session tenant association evidence is invalid", exception); + } + } + + private void requireManifestSource( + GameSessionTenantAssociationEvidence manifest, GameTenantIdentity source) { + if (source == null) { + throw new InvalidAssociationEvidenceException( + "Game Session tenant association source no longer matches its Game Design game row"); + } + Long sourceGameId = source.sourceGameId(); + GameTenantIdentity.ProvenanceKind provenanceKind = source.provenanceKind(); + if (sourceGameId == null + || provenanceKind == null + || !manifest.canonicalTenantId().equals(source.canonicalTenantId()) + || manifest.sourceGameRowIdValue() != sourceGameId + || !manifest.sourceGameTenantKey().equals(source.sourceLegacyTenantId()) + || !manifest.provenanceKind().equals(provenanceKind.name())) { + throw new InvalidAssociationEvidenceException( + "Game Session tenant association source no longer matches its Game Design game row"); + } + } + + private void requireExactReceipt(Verified verified, String signature, AssociationReceipt actual) { + if (!verified.manifest().equals(actual.manifest()) + || !verified.manifestDigest().equals(actual.manifestDigest()) + || !signature.equals(actual.ed25519Signature())) { + throw new AssociationConflictException( + "Game Session tenant association operation was reused with changed signed evidence"); + } + } + + private void requireCanonicalSignatureShape(String signature) { + if (signature == null || signature.isBlank()) { + throw new InvalidAssociationEvidenceException( + "persisted Game Session tenant association signature is missing"); + } + byte[] signatureBytes; + try { + signatureBytes = Base64.getDecoder().decode(signature); + } catch (IllegalArgumentException exception) { + throw new InvalidAssociationEvidenceException( + "persisted Game Session tenant association signature is not canonical Ed25519", + exception); + } + if (signatureBytes.length != 64 + || !Base64.getEncoder().encodeToString(signatureBytes).equals(signature)) { + throw new InvalidAssociationEvidenceException( + "persisted Game Session tenant association signature is not canonical Ed25519"); + } + } + + private void requireActiveOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Session tenant association apply requires an active Game Design owner transaction"); + } + } + + public record AssociationReceipt( + GameSessionTenantAssociationEvidence manifest, + String ed25519Signature, + String manifestDigest) { + public AssociationReceipt { + Objects.requireNonNull(manifest, "manifest"); + Objects.requireNonNull(ed25519Signature, "ed25519Signature"); + Objects.requireNonNull(manifestDigest, "manifestDigest"); + } + } + + public static final class AssociationConflictException extends IllegalStateException { + public AssociationConflictException(String message) { + super(message); + } + } + + public static final class InvalidAssociationEvidenceException extends IllegalStateException { + public InvalidAssociationEvidenceException(String message) { + super(message); + } + + public InvalidAssociationEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java index 5dca189c3f..b1e425c5fa 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java @@ -10,19 +10,24 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; import net.firedevops.firemud.gamedesign.service.impl.TenantAssociationMigrationService.ApprovedAssociation; +import net.firedevops.firemud.gamedesign.v1.GameSessionTenantAssociationManifestEvidence; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationResponse; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationResponse; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameTenantIdentityResponse; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; @@ -42,6 +47,7 @@ public class TenantIdentityGrpcService private final TenantAssociationMigrationService associationService; private final GameTenantCreationRepository creationRepository; private final GameAuthoredWorldSourceRepository authoredWorldRepository; + private final GameSessionTenantAssociationRepository gameSessionAssociationRepository; private final String workloadNamespace; public TenantIdentityGrpcService( @@ -49,11 +55,13 @@ public TenantIdentityGrpcService( TenantAssociationMigrationService associationService, GameTenantCreationRepository creationRepository, GameAuthoredWorldSourceRepository authoredWorldRepository, + GameSessionTenantAssociationRepository gameSessionAssociationRepository, @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { this.gameRepository = gameRepository; this.associationService = associationService; this.creationRepository = creationRepository; this.authoredWorldRepository = authoredWorldRepository; + this.gameSessionAssociationRepository = gameSessionAssociationRepository; this.workloadNamespace = workloadNamespace; } @@ -520,6 +528,100 @@ public void resolveAuthoredWorldSource( responseObserver.onCompleted(); } + @Override + public void resolveLegacyGameSessionTenantAssociation( + ResolveLegacyGameSessionTenantAssociationRequest request, + StreamObserver responseObserver) { + if (!isGameSessionPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified Game Session workload identity is required") + .asRuntimeException()); + return; + } + UUID requestId = parseCanonicalNonNilUuid(request.getRequestId()); + UUID operationId = parseCanonicalNonNilUuid(request.getOperationId()); + UUID tenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + long legacyTenantId; + try { + if (requestId == null + || operationId == null + || tenantId == null + || !request.getUnknownFields().asMap().isEmpty() + || !request.getLegacyGameSessionTenantId().matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("Exact association request is required"); + } + legacyTenantId = Long.parseLong(request.getLegacyGameSessionTenantId()); + } catch (IllegalArgumentException ex) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical exact association request is required") + .asRuntimeException()); + return; + } + Optional resolved; + try { + resolved = + gameSessionAssociationRepository.read( + operationId, tenantId, legacyTenantId, workloadNamespace); + } catch (IllegalArgumentException | IllegalStateException | TooManyRowsException ex) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Retained Game Session association evidence is inconsistent") + .asRuntimeException()); + return; + } catch (DataAccessException | DataAccessResourceFailureException ex) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Retained Game Session association could not be read") + .asRuntimeException()); + return; + } + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No approved retained Game Session association for the exact scope") + .asRuntimeException()); + return; + } + var receipt = resolved.orElseThrow(); + GameSessionTenantAssociationEvidence evidence = receipt.manifest(); + if (!operationId.equals(evidence.operationId()) + || !tenantId.equals(evidence.canonicalTenantId()) + || !workloadNamespace.equals(evidence.targetNamespace()) + || !request.getLegacyGameSessionTenantId().equals(evidence.legacyGameSessionTenantId()) + || !evidence.manifestDigest().equals(receipt.manifestDigest()) + || !validSignature(receipt.ed25519Signature())) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Retained association readback does not match the exact request") + .asRuntimeException()); + return; + } + responseObserver.onNext( + ResolveLegacyGameSessionTenantAssociationResponse.newBuilder() + .setRequestId(requestId.toString()) + .setManifest( + GameSessionTenantAssociationManifestEvidence.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setOperationId(evidence.operationId().toString()) + .setTargetNamespace(evidence.targetNamespace()) + .setSignerKeyId(evidence.signerKeyId()) + .setApprovedBy(evidence.approvedBy()) + .setApprovalReference(evidence.approvalReference()) + .setSignedAt(evidence.signedAt()) + .setLegacyGameSessionTenantId(evidence.legacyGameSessionTenantId()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setSourceGameRowId(evidence.sourceGameRowId()) + .setSourceGameTenantKey(evidence.sourceGameTenantKey()) + .setProvenanceKind(evidence.provenanceKind()) + .setGameSessionEvidenceDigest(evidence.gameSessionEvidenceDigest())) + .setManifestDigest(receipt.manifestDigest()) + .setEd25519Signature(receipt.ed25519Signature()) + .build()); + responseObserver.onCompleted(); + } + private boolean isAccountPeer() { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); return peer != null diff --git a/services/game-design-service/src/main/resources/application-prod.yml b/services/game-design-service/src/main/resources/application-prod.yml index 71a7ab4a82..53ba1be852 100644 --- a/services/game-design-service/src/main/resources/application-prod.yml +++ b/services/game-design-service/src/main/resources/application-prod.yml @@ -52,6 +52,9 @@ firemud: public-methods: - gamedesign.v1.TenantIdentityService/ResolveLegacyAccountTenantAssociation - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation + - gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity + - gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource + - gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index 865da4ed6d..8e5ef17edd 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -77,6 +77,7 @@ firemud: - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation - gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity - gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource + - gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-design-service/src/main/resources/db/migration/V34__game_session_tenant_association_operations.sql b/services/game-design-service/src/main/resources/db/migration/V34__game_session_tenant_association_operations.sql new file mode 100644 index 0000000000..1d014e5e4e --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V34__game_session_tenant_association_operations.sql @@ -0,0 +1,112 @@ +CREATE TABLE game_design_game_session_tenant_association_operations ( + operation_id UUID PRIMARY KEY, + schema_version INTEGER NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + signer_key_id VARCHAR(128) NOT NULL, + approved_by VARCHAR(256) NOT NULL, + approval_reference VARCHAR(512) NOT NULL, + signed_at TEXT NOT NULL, + legacy_game_session_tenant_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + source_game_row_id BIGINT NOT NULL REFERENCES game(id), + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + game_session_evidence_digest VARCHAR(71) NOT NULL, + manifest_digest VARCHAR(71) NOT NULL, + signature VARCHAR(88) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_gd_game_session_association_canonical + UNIQUE (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gd_game_session_association_retained_key + UNIQUE (target_namespace, legacy_game_session_tenant_id), + CONSTRAINT chk_gd_game_session_association_schema CHECK (schema_version = 1), + CONSTRAINT chk_gd_game_session_association_operation CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_game_session_association_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_game_session_association_approval_labels CHECK ( + char_length(signer_key_id) BETWEEN 1 AND 128 + AND char_length(approved_by) BETWEEN 1 AND 256 + AND char_length(approval_reference) BETWEEN 1 AND 512 + AND octet_length(signer_key_id) <= 128 + AND octet_length(approved_by) <= 256 + AND octet_length(approval_reference) <= 512 + AND signer_key_id !~ '[[:cntrl:]]' + AND approved_by !~ '[[:cntrl:]]' + AND approval_reference !~ '[[:cntrl:]]' + AND signer_key_id !~ '^[[:space:]]*$' + AND approved_by !~ '^[[:space:]]*$' + AND approval_reference !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_game_session_association_signed_at CHECK ( + char_length(signed_at) BETWEEN 1 AND 64 + ), + CONSTRAINT chk_gd_game_session_association_retained_key CHECK ( + legacy_game_session_tenant_id > 0 + ), + CONSTRAINT chk_gd_game_session_association_canonical CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_game_session_association_source_row CHECK (source_game_row_id > 0), + CONSTRAINT chk_gd_game_session_association_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_game_session_association_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V30') + ), + CONSTRAINT chk_gd_game_session_association_digests CHECK ( + game_session_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND manifest_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_game_session_association_signature CHECK ( + signature ~ '^[A-Za-z0-9+/]{86}==$' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_game_session_tenant_association() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Session tenant association evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game g + WHERE g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = NEW.provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) INTO source_matches; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Game Session tenant association source does not match its Game Design row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_game_session_tenant_association_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_game_session_tenant_association_operations + FOR EACH ROW EXECUTE FUNCTION enforce_gd_game_session_tenant_association(); + +CREATE FUNCTION reject_gd_game_session_tenant_association_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Session tenant association evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_game_session_tenant_association_no_truncate + BEFORE TRUNCATE ON game_design_game_session_tenant_association_operations + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_game_session_tenant_association_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java new file mode 100644 index 0000000000..1ca8d0a37f --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java @@ -0,0 +1,567 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.util.Base64; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.maintenance.GameSessionTenantAssociationManifestVerifier.Signed; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository.AssociationReceipt; +import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class GameSessionTenantAssociationRepositoryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String NAMESPACE = "game-session-association-test"; + private static final String SIGNER_KEY_ID = "gd-owner-approval-test"; + private static final String GAME_SESSION_EVIDENCE_DIGEST = "sha256:" + "a".repeat(64); + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Table ASSOCIATIONS = + DSL.table(DSL.name("game_design_game_session_tenant_association_operations")); + private static final org.jooq.Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final org.jooq.Field GAME_NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field GAME_DESCRIPTION = + DSL.field(DSL.name("description"), String.class); + private static final org.jooq.Field OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final org.jooq.Field APPROVED_BY = + DSL.field(DSL.name("approved_by"), String.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void appliesAuditedAssociationForFreshAndRetainedGameSources() throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + Signed retainedSigned = fixture.signed(fixture.retainedSource(), 901L, uuid(1)); + Signed freshSigned = fixture.signed(fixture.freshSource(), 902L, uuid(2)); + + AssociationReceipt retained = fixture.apply(retainedSigned, NAMESPACE); + AssociationReceipt fresh = fixture.apply(freshSigned, NAMESPACE); + + assertThat(retained.manifest().provenanceKind()).isEqualTo("RETAINED_GAME_V30"); + assertThat(retained.manifest().sourceGameRowIdValue()) + .isEqualTo(fixture.retainedSource().sourceGameId()); + assertThat(retained.manifest().legacyGameSessionTenantIdValue()).isEqualTo(901L); + assertThat(fresh.manifest().provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(fresh.manifest().sourceGameRowIdValue()) + .isEqualTo(fixture.freshSource().sourceGameId()); + assertThat(fresh.manifest().legacyGameSessionTenantIdValue()).isEqualTo(902L); + assertThat(fixture.read(retained)).contains(retained); + assertThat(fixture.read(fresh)).contains(fresh); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isEqualTo(2); + } + + @Test + void exactRetryReturnsSameSignedEvidenceWithoutMutatingSourceOrAssociation() throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + Signed signed = fixture.signed(fixture.freshSource(), 910L, uuid(10)); + AssociationReceipt first = fixture.apply(signed, NAMESPACE); + String originalGameXmin = fixture.gameXmin(fixture.freshSource().sourceGameId()); + + AssociationReceipt retry = fixture.apply(signed, NAMESPACE); + + assertThat(retry).isEqualTo(first); + assertThat(fixture.gameXmin(fixture.freshSource().sourceGameId())).isEqualTo(originalGameXmin); + assertThat(fixture.dsl().fetchCount(GAME)).isEqualTo(2); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isEqualTo(1); + assertThat(fixture.read(first)).contains(first); + } + + @Test + void changedSignedFieldUnderSameOperationConflictsWithoutReplacingReceipt() throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + Signed original = fixture.signed(fixture.freshSource(), 920L, uuid(20)); + AssociationReceipt committed = fixture.apply(original, NAMESPACE); + GameSessionTenantAssociationEvidence changedManifest = + withApprovalReference(original.manifest(), "changed-approved-reference"); + Signed changed = fixture.sign(changedManifest); + + assertThatThrownBy(() -> fixture.apply(changed, NAMESPACE)) + .isInstanceOf(GameSessionTenantAssociationRepository.AssociationConflictException.class) + .hasMessageContaining("reused with changed signed evidence"); + + assertThat(fixture.read(committed)).contains(committed); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + @Test + void canonicalAndRetainedKeyCollisionsFailWithoutPartialAssociationClaims() throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + Signed first = fixture.signed(fixture.freshSource(), 930L, uuid(30)); + AssociationReceipt committed = fixture.apply(first, NAMESPACE); + Signed sameCanonicalDifferentRetainedKey = + fixture.signed(fixture.freshSource(), 931L, uuid(31)); + Signed sameRetainedKeyDifferentCanonical = + fixture.signed(fixture.retainedSource(), 930L, uuid(32)); + + assertThatThrownBy(() -> fixture.apply(sameCanonicalDifferentRetainedKey, NAMESPACE)) + .isInstanceOf(GameSessionTenantAssociationRepository.AssociationConflictException.class) + .hasMessageContaining("already associated"); + assertThatThrownBy(() -> fixture.apply(sameRetainedKeyDifferentCanonical, NAMESPACE)) + .isInstanceOf(GameSessionTenantAssociationRepository.AssociationConflictException.class) + .hasMessageContaining("already associated"); + + assertThat(fixture.read(committed)).contains(committed); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(GAME)).isEqualTo(2); + } + + @Test + void absentOrContradictoryGameDesignSourcesFailWithoutAssociationMutation() throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + GameSessionTenantAssociationEvidence absentSource = + fixture.evidence( + uuid(40), + 940L, + UUID.randomUUID(), + fixture.freshSource().sourceGameId(), + "unrelated-game-key", + "NEW_GAME_ROW"); + GameSessionTenantAssociationEvidence contradictorySource = + fixture.evidence( + uuid(41), + 941L, + fixture.freshSource().canonicalTenantId(), + fixture.retainedSource().sourceGameId(), + fixture.freshSource().sourceLegacyTenantId(), + "NEW_GAME_ROW"); + + assertThatThrownBy(() -> fixture.apply(fixture.sign(absentSource), NAMESPACE)) + .isInstanceOf(GameSessionTenantAssociationRepository.AssociationConflictException.class) + .hasMessageContaining("source game row is missing"); + assertThatThrownBy(() -> fixture.apply(fixture.sign(contradictorySource), NAMESPACE)) + .isInstanceOf( + GameSessionTenantAssociationRepository.InvalidAssociationEvidenceException.class) + .hasMessageContaining("source no longer matches"); + + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isZero(); + assertThat(fixture.dsl().fetchCount(GAME)).isEqualTo(2); + } + + @Test + void concurrentExactFirstWritersReturnOneImmutableReceipt() throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + Signed signed = fixture.signed(fixture.freshSource(), 950L, uuid(50)); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> concurrentApply(fixture, signed, ready, start)); + Future second = + executor.submit(() -> concurrentApply(fixture, signed, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + AssociationReceipt firstReceipt = first.get(10, TimeUnit.SECONDS); + AssociationReceipt secondReceipt = second.get(10, TimeUnit.SECONDS); + assertThat(firstReceipt).isEqualTo(secondReceipt); + assertThat(fixture.read(firstReceipt)).contains(firstReceipt); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(GAME)).isEqualTo(2); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void ownerRollbackLeavesNoClaimAndLostAcknowledgementRetryReadsExactReceipt() throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + Signed signed = fixture.signed(fixture.freshSource(), 960L, uuid(60)); + + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> { + fixture.repository().apply(signed, fixture.trustedKeys(), NAMESPACE); + throw new IllegalStateException("simulate owner commit rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulate owner commit rollback"); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isZero(); + + fixture.apply(signed, NAMESPACE); // The commit response is intentionally discarded. + AssociationReceipt exactReadback = fixture.apply(signed, NAMESPACE); + + assertThat(exactReadback.manifest()).isEqualTo(signed.manifest()); + assertThat(exactReadback.ed25519Signature()).isEqualTo(signed.ed25519Signature()); + assertThat(exactReadback.manifestDigest()).isEqualTo(signed.manifest().manifestDigest()); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + @Test + void applyRequiresOwnerTransactionAndReadRequiresExactCommittedScope() throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + Signed signed = fixture.signed(fixture.freshSource(), 970L, uuid(70)); + + assertThatThrownBy(() -> fixture.repository().apply(signed, fixture.trustedKeys(), NAMESPACE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active Game Design owner transaction"); + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> + fixture + .repository() + .read( + signed.manifest().operationId(), + signed.manifest().canonicalTenantId(), + signed.manifest().legacyGameSessionTenantIdValue(), + NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed-outcome owner read"); + assertThatThrownBy(() -> fixture.apply(signed, "another-namespace")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("different namespace"); + Signed malformedSignature = + new Signed(signed.manifest(), signed.ed25519Signature().substring(0, 84) + "AA=="); + assertThatThrownBy(() -> fixture.apply(malformedSignature, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("signature"); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isZero(); + + AssociationReceipt committed = fixture.apply(signed, NAMESPACE); + assertThat(fixture.read(committed)).contains(committed); + assertThat( + fixture + .repository() + .read( + uuid(71), + committed.manifest().canonicalTenantId(), + committed.manifest().legacyGameSessionTenantIdValue(), + NAMESPACE)) + .isEmpty(); + assertThat( + fixture + .repository() + .read( + committed.manifest().operationId(), + fixture.retainedSource().canonicalTenantId(), + committed.manifest().legacyGameSessionTenantIdValue(), + NAMESPACE)) + .isEmpty(); + assertThat( + fixture + .repository() + .read( + committed.manifest().operationId(), + committed.manifest().canonicalTenantId(), + committed.manifest().legacyGameSessionTenantIdValue() + 1, + NAMESPACE)) + .isEmpty(); + assertThat( + fixture + .repository() + .read( + committed.manifest().operationId(), + committed.manifest().canonicalTenantId(), + committed.manifest().legacyGameSessionTenantIdValue(), + "another-namespace")) + .isEmpty(); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + @Test + void databaseRejectsAssociationUpdatesDeletesTruncatesAndContradictorySourceInsert() + throws Exception { + Fixture fixture = fixtureWithFreshAndRetainedSources(); + AssociationReceipt receipt = + fixture.apply(fixture.signed(fixture.freshSource(), 980L, uuid(80)), NAMESPACE); + + assertThatThrownBy( + () -> + fixture + .dsl() + .update(ASSOCIATIONS) + .set(APPROVED_BY, "changed-owner") + .where(OPERATION_ID.eq(receipt.manifest().operationId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .deleteFrom(ASSOCIATIONS) + .where(OPERATION_ID.eq(receipt.manifest().operationId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute("TRUNCATE game_design_game_session_tenant_association_operations")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + + assertThatThrownBy( + () -> + fixture + .dsl() + .insertInto(ASSOCIATIONS) + .set(OPERATION_ID, uuid(81)) + .set(DSL.field(DSL.name("schema_version"), Integer.class), 1) + .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) + .set(DSL.field(DSL.name("signer_key_id"), String.class), SIGNER_KEY_ID) + .set(DSL.field(DSL.name("approved_by"), String.class), "owner@example.test") + .set( + DSL.field(DSL.name("approval_reference"), String.class), + "source-contradiction-test") + .set(DSL.field(DSL.name("signed_at"), String.class), "2026-10-01T00:00:00Z") + .set(DSL.field(DSL.name("legacy_game_session_tenant_id"), Long.class), 981L) + .set( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class), + receipt.manifest().canonicalTenantId()) + .set( + DSL.field(DSL.name("source_game_row_id"), Long.class), + fixture.freshSource().sourceGameId()) + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "contradictory-source-key") + .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") + .set( + DSL.field(DSL.name("game_session_evidence_digest"), String.class), + GAME_SESSION_EVIDENCE_DIGEST) + .set( + DSL.field(DSL.name("manifest_digest"), String.class), + receipt.manifestDigest()) + .set(DSL.field(DSL.name("signature"), String.class), receipt.ed25519Signature()) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("does not match its Game Design row"); + + assertThat(fixture.read(receipt)).contains(receipt); + assertThat(fixture.dsl().fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + private AssociationReceipt concurrentApply( + Fixture fixture, Signed signed, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + return fixture.apply(signed, NAMESPACE); + } + + private Fixture fixtureWithFreshAndRetainedSources() throws Exception { + String schema = "game_design_gs_assoc_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("29")); + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Long retainedGameId = + legacyDsl + .insertInto(GAME) + .set(TENANT_ID, "retained-game-design-owner-source") + .set(GAME_NAME, "Retained Source Game") + .set(GAME_DESCRIPTION, "Persisted before canonical tenant identities") + .returning(GAME_ID) + .fetchOne(GAME_ID); + assertThat(retainedGameId).isNotNull(); + + migrate(dataSource, schema, null); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameRepository gameRepository = new GameRepository(dsl); + GameSessionTenantAssociationRepository repository = + new GameSessionTenantAssociationRepository(dsl, gameRepository); + UUID retainedCanonicalTenantId = + dsl.select(DSL.field(DSL.name("canonical_tenant_id"), UUID.class)) + .from(GAME) + .where(GAME_ID.eq(retainedGameId)) + .fetchOne(DSL.field(DSL.name("canonical_tenant_id"), UUID.class)); + GameTenantIdentity retainedSource = + gameRepository + .findRuntimeTenantIdentityByCanonicalTenantId(retainedCanonicalTenantId) + .orElseThrow(); + + Game freshGame = new Game(); + freshGame.setTenantId("fresh-game-design-owner-source"); + freshGame.setName("Fresh Source Game"); + freshGame.setDescription("Persisted after canonical tenant identities"); + Game persistedFreshGame = transactionTemplate.execute(status -> gameRepository.save(freshGame)); + GameTenantIdentity freshSource = + gameRepository + .findRuntimeTenantIdentityByCanonicalTenantId( + Objects.requireNonNull(persistedFreshGame).getCanonicalTenantId()) + .orElseThrow(); + KeyPair ownerKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + Map trustedKeys = + Map.of( + SIGNER_KEY_ID, Base64.getEncoder().encodeToString(ownerKey.getPublic().getEncoded())); + return new Fixture( + dsl, repository, transactionTemplate, ownerKey, trustedKeys, retainedSource, freshSource); + } + + private DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private GameSessionTenantAssociationEvidence withApprovalReference( + GameSessionTenantAssociationEvidence original, String approvalReference) { + return new GameSessionTenantAssociationEvidence( + original.schemaVersion(), + original.operationId(), + original.targetNamespace(), + original.signerKeyId(), + original.approvedBy(), + approvalReference, + original.signedAt(), + original.legacyGameSessionTenantId(), + original.canonicalTenantId(), + original.sourceGameRowId(), + original.sourceGameTenantKey(), + original.provenanceKind(), + original.gameSessionEvidenceDigest()); + } + + private UUID uuid(int suffix) { + return UUID.fromString(String.format("%08d-2222-4222-8222-222222222222", suffix)); + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for concurrent association apply"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for concurrent association apply", exception); + } + } + + private record Fixture( + DSLContext dsl, + GameSessionTenantAssociationRepository repository, + TransactionTemplate transactionTemplate, + KeyPair ownerKey, + Map trustedKeys, + GameTenantIdentity retainedSource, + GameTenantIdentity freshSource) { + Signed signed(GameTenantIdentity source, long retainedGameSessionTenantId, UUID operationId) + throws Exception { + return sign( + evidence( + operationId, + retainedGameSessionTenantId, + source.canonicalTenantId(), + source.sourceGameId(), + source.sourceLegacyTenantId(), + source.provenanceKind().name())); + } + + GameSessionTenantAssociationEvidence evidence( + UUID operationId, + long retainedGameSessionTenantId, + UUID canonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) { + return new GameSessionTenantAssociationEvidence( + 1, + operationId, + NAMESPACE, + SIGNER_KEY_ID, + "approved-owner@example.test", + "retained-session-audit-" + operationId, + "2026-10-01T00:00:00Z", + Long.toString(retainedGameSessionTenantId), + canonicalTenantId, + Long.toString(sourceGameRowId), + sourceGameTenantKey, + provenanceKind, + GAME_SESSION_EVIDENCE_DIGEST); + } + + Signed sign(GameSessionTenantAssociationEvidence manifest) throws Exception { + Signature signer = Signature.getInstance("Ed25519"); + signer.initSign(ownerKey.getPrivate()); + signer.update(manifest.preimage()); + return new Signed(manifest, Base64.getEncoder().encodeToString(signer.sign())); + } + + AssociationReceipt apply(Signed signed, String exactNamespace) { + AssociationReceipt receipt = + transactionTemplate.execute( + status -> repository.apply(signed, trustedKeys, exactNamespace)); + return Objects.requireNonNull(receipt); + } + + Optional read(AssociationReceipt receipt) { + return repository.read( + receipt.manifest().operationId(), + receipt.manifest().canonicalTenantId(), + receipt.manifest().legacyGameSessionTenantIdValue(), + receipt.manifest().targetNamespace()); + } + + String gameXmin(long gameId) { + return dsl.fetch("SELECT xmin::text AS xmin FROM game WHERE id = ?", gameId) + .getFirst() + .get("xmin", String.class); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifierTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifierTest.java new file mode 100644 index 0000000000..afa939c67e --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/maintenance/GameSessionTenantAssociationManifestVerifierTest.java @@ -0,0 +1,448 @@ +package unit.net.firedevops.firemud.gamedesign.maintenance; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.time.Instant; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamedesign.maintenance.GameSessionTenantAssociationManifestVerifier; +import net.firedevops.firemud.gamedesign.maintenance.GameSessionTenantAssociationManifestVerifier.Signed; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifest.Entry; +import net.firedevops.firemud.gamedesign.maintenance.TenantAssociationManifestVerifier; +import org.junit.jupiter.api.Test; + +class GameSessionTenantAssociationManifestVerifierTest { + @Test + void verifiesExactOwnerSignedReadbackAndRecomputesDigest() throws Exception { + KeyPair ownerKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + GameSessionTenantAssociationEvidence manifest = evidence(); + Map trustedKeys = trustedKeys("owner-key-2026", ownerKey); + Signed signed = signed(manifest, ownerKey); + + var verified = GameSessionTenantAssociationManifestVerifier.verify(signed, trustedKeys); + assertThat(verified.manifest()).isEqualTo(manifest); + assertThat(verified.manifestDigest()).isEqualTo(manifest.manifestDigest()); + assertThat(GameSessionTenantAssociationManifestVerifier.verify(signed, trustedKeys)) + .isEqualTo(verified); + } + + @Test + void everyMutableManifestFieldIsSignatureBound() throws Exception { + KeyPair ownerKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + GameSessionTenantAssociationEvidence manifest = evidence(); + Signed signed = signed(manifest, ownerKey); + String publicKey = Base64.getEncoder().encodeToString(ownerKey.getPublic().getEncoded()); + Map trustedKeys = + Map.of("owner-key-2026", publicKey, "owner-key-2027", publicKey); + + for (GameSessionTenantAssociationEvidence changed : changedFields(manifest)) { + assertThat(changed.preimage()).isNotEqualTo(manifest.preimage()); + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + new Signed(changed, signed.ed25519Signature()), trustedKeys)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("signature is invalid"); + } + assertThatThrownBy(() -> copyWithSchemaVersion(manifest, 2)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("schema version"); + } + + @Test + void rejectsAbsentUntrustedWrongPurposeMalformedAndInvalidSignatures() throws Exception { + KeyPair ownerKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + KeyPair unrelatedKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + GameSessionTenantAssociationEvidence manifest = evidence(); + Signed signed = signed(manifest, ownerKey); + Map trustedKeys = trustedKeys("owner-key-2026", ownerKey); + + assertThatThrownBy(() -> GameSessionTenantAssociationManifestVerifier.verify(null, trustedKeys)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + new Signed(null, signed.ed25519Signature()), trustedKeys)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> GameSessionTenantAssociationManifestVerifier.verify(signed, Map.of())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not trusted"); + + GameSessionTenantAssociationEvidence wrongPurpose = + copyWithSignerKeyId(manifest, "account-owner-key"); + Signed accountPurposeSignature = signed(wrongPurpose, unrelatedKey); + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + accountPurposeSignature, trustedKeys)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not trusted"); + + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + signed, Map.of("owner-key-2026", "not base64"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + signed, + Map.of("owner-key-2026", Base64.getEncoder().encodeToString(new byte[32])))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("cannot be verified"); + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + new Signed(manifest, "%%%"), trustedKeys)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + new Signed(manifest, Base64.getEncoder().encodeToString(new byte[63])), + trustedKeys)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("64-byte"); + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + signed(manifest, unrelatedKey), trustedKeys)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("signature is invalid"); + } + + @Test + void accountAssociationManifestSignatureDoesNotVerifyAsGameSessionAssociation() throws Exception { + KeyPair ownerKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + GameSessionTenantAssociationEvidence gameSessionManifest = evidence(); + TenantAssociationManifest accountManifest = + new TenantAssociationManifest( + 1, + gameSessionManifest.operationId(), + gameSessionManifest.targetNamespace(), + gameSessionManifest.signerKeyId(), + gameSessionManifest.approvedBy(), + gameSessionManifest.approvalReference(), + Instant.parse(gameSessionManifest.signedAt()), + List.of( + new Entry( + 41, + gameSessionManifest.sourceGameTenantKey(), + gameSessionManifest.canonicalTenantId(), + gameSessionManifest.sourceGameRowIdValue(), + "sha256:" + "b".repeat(64)))); + Signature accountManifestSigner = Signature.getInstance("Ed25519"); + accountManifestSigner.initSign(ownerKey.getPrivate()); + accountManifestSigner.update(TenantAssociationManifestVerifier.preimage(accountManifest)); + Signed crossDomainSignature = + new Signed( + gameSessionManifest, Base64.getEncoder().encodeToString(accountManifestSigner.sign())); + + assertThatThrownBy( + () -> + GameSessionTenantAssociationManifestVerifier.verify( + crossDomainSignature, trustedKeys("owner-key-2026", ownerKey))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("signature is invalid"); + } + + private static GameSessionTenantAssociationEvidence evidence() { + return new GameSessionTenantAssociationEvidence( + 1, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + "firemud", + "owner-key-2026", + "owner 🧙", + "review café-🐉", + Instant.parse("2026-10-01T00:00:00Z").toString(), + "9007199254740993", + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "42", + "legacy-game-key-42", + "RETAINED_GAME_V30", + "sha256:" + "a".repeat(64)); + } + + private static java.util.List changedFields( + GameSessionTenantAssociationEvidence source) { + return java.util.List.of( + copy(source, "9007199254740994", source.sourceGameRowId()), + copyWithTargetNamespace(source, "firemud-dev"), + copyWithSignerKeyId(source, "owner-key-2027"), + copyWithApproval(source, "another owner", source.approvalReference()), + copyWithApproval(source, source.approvedBy(), "another-review-reference"), + copyWithSignedAt(source, "2026-10-01T00:00:01Z"), + copyWithOperationId(source, UUID.fromString("33333333-3333-4333-8333-333333333333")), + copyWithTenantId(source, UUID.fromString("33333333-3333-4333-8333-333333333333")), + copy(source, source.legacyGameSessionTenantId(), "43"), + copyWithSourceGameTenantKey(source, "another-source-key"), + copyWithProvenanceKind(source, "NEW_GAME_ROW"), + copyWithGameSessionEvidenceDigest(source, "sha256:" + "b".repeat(64))); + } + + private static Map trustedKeys(String keyId, KeyPair keyPair) { + return Map.of(keyId, Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded())); + } + + private static Signed signed(GameSessionTenantAssociationEvidence manifest, KeyPair keyPair) + throws Exception { + Signature signer = Signature.getInstance("Ed25519"); + signer.initSign(keyPair.getPrivate()); + signer.update(manifest.preimage()); + return new Signed(manifest, Base64.getEncoder().encodeToString(signer.sign())); + } + + private static GameSessionTenantAssociationEvidence copy( + GameSessionTenantAssociationEvidence source, + String legacyGameSessionTenantId, + String sourceGameRowId) { + return make( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + legacyGameSessionTenantId, + source.canonicalTenantId(), + sourceGameRowId, + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithSchemaVersion( + GameSessionTenantAssociationEvidence source, int schemaVersion) { + return make( + source, + schemaVersion, + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithTargetNamespace( + GameSessionTenantAssociationEvidence source, String targetNamespace) { + return make( + source, + source.schemaVersion(), + source.operationId(), + targetNamespace, + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithSignerKeyId( + GameSessionTenantAssociationEvidence source, String signerKeyId) { + return make( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + signerKeyId, + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithOperationId( + GameSessionTenantAssociationEvidence source, UUID operationId) { + return make( + source, + source.schemaVersion(), + operationId, + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithApproval( + GameSessionTenantAssociationEvidence source, String approvedBy, String approvalReference) { + return make( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + approvedBy, + approvalReference, + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithSignedAt( + GameSessionTenantAssociationEvidence source, String signedAt) { + return make( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + signedAt, + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithTenantId( + GameSessionTenantAssociationEvidence source, UUID canonicalTenantId) { + return make( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + canonicalTenantId, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithSourceGameTenantKey( + GameSessionTenantAssociationEvidence source, String sourceGameTenantKey) { + return make( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + sourceGameTenantKey, + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithProvenanceKind( + GameSessionTenantAssociationEvidence source, String provenanceKind) { + return make( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + provenanceKind, + source.gameSessionEvidenceDigest()); + } + + private static GameSessionTenantAssociationEvidence copyWithGameSessionEvidenceDigest( + GameSessionTenantAssociationEvidence source, String gameSessionEvidenceDigest) { + return make( + source, + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + gameSessionEvidenceDigest); + } + + private static GameSessionTenantAssociationEvidence make( + GameSessionTenantAssociationEvidence source, + int schemaVersion, + UUID operationId, + String targetNamespace, + String signerKeyId, + String approvedBy, + String approvalReference, + String signedAt, + String legacyGameSessionTenantId, + UUID canonicalTenantId, + String sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind, + String gameSessionEvidenceDigest) { + return new GameSessionTenantAssociationEvidence( + schemaVersion, + operationId, + targetNamespace, + signerKeyId, + approvedBy, + approvalReference, + signedAt, + legacyGameSessionTenantId, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + gameSessionEvidenceDigest); + } + + private static GameSessionTenantAssociationEvidence copyWithProvenance( + GameSessionTenantAssociationEvidence source, String provenanceKind) { + return copyWithProvenanceKind(source, provenanceKind); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java new file mode 100644 index 0000000000..c4e1388950 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java @@ -0,0 +1,272 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Base64; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository.AssociationReceipt; +import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationResponse; +import org.junit.jupiter.api.Test; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.FileSystemResource; + +class GameSessionTenantAssociationGrpcTest { + private static final UUID OPERATION = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String READ_REQUEST = "33333333-3333-4333-8333-333333333333"; + private static final String GAME_SESSION = "spiffe://firemud/ns/test/sa/game-session-service"; + private final GameSessionTenantAssociationRepository repository = + mock(GameSessionTenantAssociationRepository.class); + private final TenantIdentityGrpcService service = + new TenantIdentityGrpcService( + mock(GameRepository.class), + mock(TenantAssociationMigrationService.class), + mock(GameTenantCreationRepository.class), + mock(GameAuthoredWorldSourceRepository.class), + repository, + "test"); + + @Test + void exactGameSessionPeerPrecedesSyntaxAndOwnerReads() { + for (String peer : + new String[] { + null, + "spiffe://firemud/ns/test/sa/account-service", + "spiffe://firemud/ns/other/sa/game-session-service" + }) { + Observer observer = + call(ResolveLegacyGameSessionTenantAssociationRequest.getDefaultInstance(), peer); + assertThat(observer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + verifyNoInteractions(repository); + } + + @Test + void aliasesOverflowNilAndUnknownFieldsDenyBeforeOwnerAccess() { + for (String key : new String[] {"", "0", "01", "-1", "1.0", "9223372036854775808", " 41"}) { + assertThat( + call(request().toBuilder().setLegacyGameSessionTenantId(key).build(), GAME_SESSION) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + } + assertThat( + call( + request().toBuilder() + .setOperationId("00000000-0000-0000-0000-000000000000") + .build(), + GAME_SESSION) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + call( + request().toBuilder() + .setRequestId("33333333-3333-4333-8333-33333333333") + .build(), + GAME_SESSION) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + call( + request().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(), + GAME_SESSION) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @Test + void exactReadCarriesCompleteImmutableManifestAndSeparateReadEcho() { + GameSessionTenantAssociationEvidence evidence = evidence(); + String signature = Base64.getEncoder().encodeToString(new byte[64]); + when(repository.read(OPERATION, TENANT, 41L, "test")) + .thenReturn( + Optional.of(new AssociationReceipt(evidence, signature, evidence.manifestDigest()))); + Observer observer = call(request(), GAME_SESSION); + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.getRequestId()).isEqualTo(READ_REQUEST); + var manifest = observer.value.getManifest(); + assertThat(manifest.getSchemaVersion()).isEqualTo(1); + assertThat(manifest.getOperationId()).isEqualTo(OPERATION.toString()); + assertThat(manifest.getTargetNamespace()).isEqualTo("test"); + assertThat(manifest.getSignerKeyId()).isEqualTo(evidence.signerKeyId()); + assertThat(manifest.getApprovedBy()).isEqualTo(evidence.approvedBy()); + assertThat(manifest.getApprovalReference()).isEqualTo(evidence.approvalReference()); + assertThat(manifest.getSignedAt()).isEqualTo(evidence.signedAt()); + assertThat(manifest.getLegacyGameSessionTenantId()).isEqualTo("41"); + assertThat(manifest.getCanonicalTenantId()).isEqualTo(TENANT.toString()); + assertThat(manifest.getSourceGameRowId()).isEqualTo(evidence.sourceGameRowId()); + assertThat(manifest.getSourceGameTenantKey()).isEqualTo(evidence.sourceGameTenantKey()); + assertThat(manifest.getProvenanceKind()).isEqualTo(evidence.provenanceKind()); + assertThat(manifest.getGameSessionEvidenceDigest()) + .isEqualTo(evidence.gameSessionEvidenceDigest()); + assertThat(observer.value.getManifestDigest()).isEqualTo(evidence.manifestDigest()); + assertThat(observer.value.getEd25519Signature()).isEqualTo(signature); + } + + @Test + void absentContradictoryAndUnavailableEvidenceNeverReturnsPartialContent() { + when(repository.read(OPERATION, TENANT, 41L, "test")) + .thenReturn(Optional.empty()) + .thenThrow(new IllegalStateException("contradictory stored evidence")) + .thenThrow(new org.jooq.exception.DataAccessException("storage unavailable")); + assertThat(call(request(), GAME_SESSION).error).isEqualTo(Status.Code.NOT_FOUND); + assertThat(call(request(), GAME_SESSION).error).isEqualTo(Status.Code.FAILED_PRECONDITION); + Observer unavailable = call(request(), GAME_SESSION); + assertThat(unavailable.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.value).isNull(); + assertThat(unavailable.completed).isFalse(); + } + + @Test + void changedReadScopeDigestAndSignatureDenyWithoutPartialContent() { + GameSessionTenantAssociationEvidence exact = evidence(); + String signature = Base64.getEncoder().encodeToString(new byte[64]); + for (AssociationReceipt wrong : + new AssociationReceipt[] { + receipt(withScope(UUID.randomUUID(), TENANT, "test", "41"), signature), + receipt(withScope(OPERATION, UUID.randomUUID(), "test", "41"), signature), + receipt(withScope(OPERATION, TENANT, "other", "41"), signature), + receipt(withScope(OPERATION, TENANT, "test", "42"), signature), + new AssociationReceipt(exact, signature, "sha256:" + "b".repeat(64)), + new AssociationReceipt(exact, "invalid-signature", exact.manifestDigest()) + }) { + when(repository.read(OPERATION, TENANT, 41L, "test")).thenReturn(Optional.of(wrong)); + Observer observer = call(request(), GAME_SESSION); + assertThat(observer.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + } + + @Test + void productionAndDefaultBearerBypassKeepExactProtectedSourceReadsAligned() throws Exception { + Set required = + Set.of( + "gamedesign.v1.TenantIdentityService/ResolveRuntimeTenantIdentity", + "gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource", + "gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation"); + for (String name : new String[] {"application.yml", "application-prod.yml"}) { + Set methods = new HashSet<>(); + for (PropertySource source : + new YamlPropertySourceLoader() + .load(name, new FileSystemResource("src/main/resources/" + name))) { + for (int index = 0; index < 20; index++) { + Object method = source.getProperty("firemud.auth.grpc.public-methods[" + index + "]"); + if (method != null) { + methods.add(method.toString()); + } + } + } + assertThat(methods).containsAll(required); + } + } + + private ResolveLegacyGameSessionTenantAssociationRequest request() { + return ResolveLegacyGameSessionTenantAssociationRequest.newBuilder() + .setRequestId(READ_REQUEST) + .setOperationId(OPERATION.toString()) + .setCanonicalTenantId(TENANT.toString()) + .setLegacyGameSessionTenantId("41") + .build(); + } + + private GameSessionTenantAssociationEvidence evidence() { + return new GameSessionTenantAssociationEvidence( + 1, + OPERATION, + "test", + "owner-key", + "owner", + "approval-41", + "2026-10-01T00:00:00Z", + "41", + TENANT, + "7", + "source-key", + "RETAINED_GAME_V30", + "sha256:" + "a".repeat(64)); + } + + private GameSessionTenantAssociationEvidence withScope( + UUID operation, UUID tenant, String namespace, String legacyKey) { + GameSessionTenantAssociationEvidence source = evidence(); + return new GameSessionTenantAssociationEvidence( + source.schemaVersion(), + operation, + namespace, + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + legacyKey, + tenant, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } + + private AssociationReceipt receipt( + GameSessionTenantAssociationEvidence manifest, String signature) { + return new AssociationReceipt(manifest, signature, manifest.manifestDigest()); + } + + private Observer call(ResolveLegacyGameSessionTenantAssociationRequest request, String peer) { + Observer observer = new Observer(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + peer == null ? null : GrpcPeerIdentity.parseUri(peer).orElseThrow()) + .run(() -> service.resolveLegacyGameSessionTenantAssociation(request, observer)); + return observer; + } + + private static final class Observer + implements StreamObserver { + private ResolveLegacyGameSessionTenantAssociationResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ResolveLegacyGameSessionTenantAssociationResponse value) { + this.value = value; + } + + @Override + public void onError(Throwable error) { + this.error = Status.fromThrowable(error).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java index 11d89fd643..3c21b864b8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java @@ -26,6 +26,7 @@ import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameSessionTenantAssociationRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantIdentity; import net.firedevops.firemud.gamedesign.service.impl.TenantAssociationMigrationService.ApprovedAssociation; @@ -80,9 +81,16 @@ class TenantIdentityGrpcServiceTest { mock(GameTenantCreationRepository.class); private final GameAuthoredWorldSourceRepository authoredWorldRepository = mock(GameAuthoredWorldSourceRepository.class); + private final GameSessionTenantAssociationRepository gameSessionAssociationRepository = + mock(GameSessionTenantAssociationRepository.class); private final TenantIdentityGrpcService service = new TenantIdentityGrpcService( - repository, associationService, creationRepository, authoredWorldRepository, "test"); + repository, + associationService, + creationRepository, + authoredWorldRepository, + gameSessionAssociationRepository, + "test"); @Test void authoredSourceReadRequiresExactGameSessionPeerBeforeOwnerAccess() { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java index ffbb3818ac..5a73e5ea7f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClient.java @@ -2,6 +2,7 @@ import io.grpc.ManagedChannel; import java.io.IOException; +import java.util.Base64; import java.util.UUID; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; @@ -13,9 +14,12 @@ import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationResponse; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; @@ -25,9 +29,16 @@ public final class GameDesignRuntimeTenantIdentityClient extends AbstractReloadingBlockingGrpcClient< TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub> { private static final long CALL_DEADLINE_SECONDS = 5L; + private static final int ED25519_SIGNATURE_BYTES = 64; private final String workloadNamespace; + /** A validated owner receipt; it does not prove retained-row agreement or catalog admission. */ + public record LegacyGameSessionTenantAssociationReceipt( + GameSessionTenantAssociationEvidence evidence, + String manifestDigest, + String ed25519Signature) {} + public GameDesignRuntimeTenantIdentityClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProps, @@ -180,6 +191,121 @@ public AuthoredWorldSourceEvidence resolveAuthoredWorldSource( return evidence; } + /** + * Reads one exact approved retained Game Session association through the authenticated Game + * Design workload channel. This validates owner evidence only; it does not inspect or persist + * Game Session's retained rows, enroll a catalog entry, or grant admission. + */ + public LegacyGameSessionTenantAssociationReceipt resolveLegacyGameSessionTenantAssociation( + String canonicalTenantId, + String operationId, + String legacyGameSessionTenantId, + String requestId) { + UUID tenantUuid = parseCanonicalNonNilUuid(canonicalTenantId, "canonical tenant ID"); + UUID operationUuid = parseCanonicalNonNilUuid(operationId, "operation ID"); + String retainedTenantKey = + parseCanonicalPositiveBigint(legacyGameSessionTenantId, "legacy Game Session tenant ID"); + UUID requestUuid = parseCanonicalNonNilUuid(requestId, "request ID"); + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association client is not initialized"); + } + + ResolveLegacyGameSessionTenantAssociationResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveLegacyGameSessionTenantAssociation( + ResolveLegacyGameSessionTenantAssociationRequest.newBuilder() + .setRequestId(requestUuid.toString()) + .setOperationId(operationUuid.toString()) + .setCanonicalTenantId(tenantUuid.toString()) + .setLegacyGameSessionTenantId(retainedTenantKey) + .build()); + if (!response.getUnknownFields().asMap().isEmpty()) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association response contains " + + "unsupported fields"); + } + if (!response.hasManifest()) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association response has no manifest"); + } + UUID echoedRequestId; + try { + echoedRequestId = parseCanonicalNonNilUuid(response.getRequestId(), "response request ID"); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association response request echo is invalid", + exception); + } + if (!requestUuid.equals(echoedRequestId)) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association response does not match " + + "the exact request echo"); + } + + var manifest = response.getManifest(); + if (!manifest.getUnknownFields().asMap().isEmpty()) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association manifest contains " + + "unsupported fields"); + } + GameSessionTenantAssociationEvidence evidence; + try { + evidence = + new GameSessionTenantAssociationEvidence( + manifest.getSchemaVersion(), + parseCanonicalNonNilUuid(manifest.getOperationId(), "manifest operation ID"), + manifest.getTargetNamespace(), + manifest.getSignerKeyId(), + manifest.getApprovedBy(), + manifest.getApprovalReference(), + manifest.getSignedAt(), + manifest.getLegacyGameSessionTenantId(), + parseCanonicalNonNilUuid( + manifest.getCanonicalTenantId(), "manifest canonical tenant ID"), + manifest.getSourceGameRowId(), + manifest.getSourceGameTenantKey(), + manifest.getProvenanceKind(), + manifest.getGameSessionEvidenceDigest()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association manifest is invalid", exception); + } + + String signature = response.getEd25519Signature(); + byte[] signatureBytes; + try { + signatureBytes = Base64.getDecoder().decode(signature); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association signature is invalid", exception); + } + if (signatureBytes.length != ED25519_SIGNATURE_BYTES + || !Base64.getEncoder().encodeToString(signatureBytes).equals(signature)) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association signature is not canonical " + + "Ed25519 base64"); + } + + String manifestDigest = response.getManifestDigest(); + if (!evidence.manifestDigest().equals(manifestDigest)) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association manifest digest does not match " + + "its evidence"); + } + if (!workloadNamespace.equals(evidence.targetNamespace()) + || !operationUuid.equals(evidence.operationId()) + || !tenantUuid.equals(evidence.canonicalTenantId()) + || !retainedTenantKey.equals(evidence.legacyGameSessionTenantId())) { + throw new IllegalStateException( + "Game Design retained Game Session tenant association response does not match " + + "the exact request"); + } + return new LegacyGameSessionTenantAssociationReceipt(evidence, manifestDigest, signature); + } + private static UUID parseCanonicalNonNilUuid(String value, String label) { if (value == null) { throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); @@ -196,6 +322,22 @@ private static UUID parseCanonicalNonNilUuid(String value, String label) { return parsed; } + private static String parseCanonicalPositiveBigint(String value, String label) { + if (value == null || value.length() > 19 || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be canonical positive BIGINT text"); + } + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(label + " must be canonical positive BIGINT text"); + } + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + label + " must fit a positive PostgreSQL BIGINT", exception); + } + return value; + } + private static CommonGrpcClientProperties requireGameSessionMtls( CommonGrpcClientProperties tlsProps) { if (tlsProps == null) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java index 41bc8229d0..72c0d28e51 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignRuntimeTenantIdentityClientTest.java @@ -18,6 +18,7 @@ import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Base64; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -27,9 +28,13 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamedesign.v1.GameSessionTenantAssociationManifestEvidence; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationResponse; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityRequest; import net.firedevops.firemud.gamedesign.v1.ResolveRuntimeTenantIdentityResponse; import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; @@ -47,6 +52,11 @@ class GameDesignRuntimeTenantIdentityClientTest { UUID.fromString("33333333-3333-4333-8333-333333333333"); private static final UUID REGISTRATION_REQUEST_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final String LEGACY_GAME_SESSION_TENANT_ID = "23"; + // The client checks canonical Ed25519 signature shape, not signature trust or validity. + private static final String SIGNATURE_SHAPE_FIXTURE = + Base64.getEncoder().encodeToString(new byte[64]); + private static final String ASSOCIATION_SOURCE_DIGEST = "sha256:" + "a".repeat(64); @Test void authoredSourceReadBindsCompleteReceiptAndSeparateReadIdentity() throws Exception { @@ -184,6 +194,248 @@ void authoredSourceValidatesRequestBeforeStubAndPreservesUnavailableStatus() thr .isSameAs(unavailable); } + @Test + void retainedAssociationReadReturnsCompleteImmutableReceiptAndRetriesExactly() throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + ResolveLegacyGameSessionTenantAssociationResponse response = associationResponse(); + when(stub.resolveLegacyGameSessionTenantAssociation(any())) + .thenReturn(response) + .thenReturn(response); + GameDesignRuntimeTenantIdentityClient client = newClient(stub); + + GameDesignRuntimeTenantIdentityClient.LegacyGameSessionTenantAssociationReceipt first = + client.resolveLegacyGameSessionTenantAssociation( + TENANT_ID.toString(), + SOURCE_OPERATION_ID.toString(), + LEGACY_GAME_SESSION_TENANT_ID, + REQUEST_ID.toString()); + GameDesignRuntimeTenantIdentityClient.LegacyGameSessionTenantAssociationReceipt retry = + client.resolveLegacyGameSessionTenantAssociation( + TENANT_ID.toString(), + SOURCE_OPERATION_ID.toString(), + LEGACY_GAME_SESSION_TENANT_ID, + REQUEST_ID.toString()); + + assertThat(first).isEqualTo(retry); + assertThat(first.evidence()).isEqualTo(associationEvidence()); + assertThat(first.manifestDigest()).isEqualTo(associationEvidence().manifestDigest()); + assertThat(first.ed25519Signature()).isEqualTo(SIGNATURE_SHAPE_FIXTURE); + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(ResolveLegacyGameSessionTenantAssociationRequest.class); + verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub, times(2)).resolveLegacyGameSessionTenantAssociation(requestCaptor.capture()); + assertThat(requestCaptor.getAllValues()) + .allSatisfy( + request -> { + assertThat(request.getRequestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(request.getOperationId()).isEqualTo(SOURCE_OPERATION_ID.toString()); + assertThat(request.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(request.getLegacyGameSessionTenantId()) + .isEqualTo(LEGACY_GAME_SESSION_TENANT_ID); + }); + verify(stub, never()).resolveRuntimeTenantIdentity(any()); + verify(stub, never()).resolveAuthoredWorldSource(any()); + verify(stub, never()).resolveLegacyAccountTenantAssociation(any()); + } + + @Test + void retainedAssociationRejectsAliasesNilAndBigintOverflowBeforeRpc() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignRuntimeTenantIdentityClient client = newClientWithoutStub(channelFactory); + List invalidRequests = + List.of( + new String[] { + "AB426BB3-A733-43F0-9C8E-2E379CBDF7EC", + SOURCE_OPERATION_ID.toString(), + "9", + REQUEST_ID.toString() + }, + new String[] { + "00000000-0000-0000-0000-000000000000", + SOURCE_OPERATION_ID.toString(), + "9", + REQUEST_ID.toString() + }, + new String[] { + TENANT_ID.toString(), + "33333333-3333-4333-8333-33333333333", + "9", + REQUEST_ID.toString() + }, + new String[] { + TENANT_ID.toString(), + "00000000-0000-0000-0000-000000000000", + "9", + REQUEST_ID.toString() + }, + new String[] { + TENANT_ID.toString(), SOURCE_OPERATION_ID.toString(), "0", REQUEST_ID.toString() + }, + new String[] { + TENANT_ID.toString(), SOURCE_OPERATION_ID.toString(), "09", REQUEST_ID.toString() + }, + new String[] { + TENANT_ID.toString(), SOURCE_OPERATION_ID.toString(), "+9", REQUEST_ID.toString() + }, + new String[] { + TENANT_ID.toString(), + SOURCE_OPERATION_ID.toString(), + "9223372036854775808", + REQUEST_ID.toString() + }, + new String[] { + TENANT_ID.toString(), + SOURCE_OPERATION_ID.toString(), + "9", + "22222222-2222-4222-8222-22222222222" + }, + new String[] { + TENANT_ID.toString(), + SOURCE_OPERATION_ID.toString(), + "9", + "00000000-0000-0000-0000-000000000000" + }); + + for (String[] invalid : invalidRequests) { + assertThatThrownBy( + () -> + client.resolveLegacyGameSessionTenantAssociation( + invalid[0], invalid[1], invalid[2], invalid[3])) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(channelFactory); + } + + @Test + void retainedAssociationRejectsMissingManifestAndUnknownEnvelopeFields() throws Exception { + assertAssociationRejected( + ResolveLegacyGameSessionTenantAssociationResponse.newBuilder() + .setRequestId(REQUEST_ID.toString()) + .build(), + "has no manifest"); + assertAssociationRejected( + associationResponse().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(), + "unsupported fields"); + GameSessionTenantAssociationManifestEvidence manifestWithUnknownField = + associationResponse().getManifest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertAssociationRejected( + associationResponse().toBuilder().setManifest(manifestWithUnknownField).build(), + "manifest contains unsupported fields"); + } + + @Test + void retainedAssociationRejectsEveryChangedManifestFieldAgainstOriginalDigest() throws Exception { + ResolveLegacyGameSessionTenantAssociationResponse valid = associationResponse(); + GameSessionTenantAssociationManifestEvidence manifest = valid.getManifest(); + List changedManifests = + List.of( + manifest.toBuilder().setOperationId(REQUEST_ID.toString()).build(), + manifest.toBuilder().setTargetNamespace("other").build(), + manifest.toBuilder().setSignerKeyId("other-signer").build(), + manifest.toBuilder().setApprovedBy("other-approver").build(), + manifest.toBuilder().setApprovalReference("other-reference").build(), + manifest.toBuilder().setSignedAt("2026-09-30T12:01:00Z").build(), + manifest.toBuilder().setLegacyGameSessionTenantId("24").build(), + manifest.toBuilder().setCanonicalTenantId(REQUEST_ID.toString()).build(), + manifest.toBuilder().setSourceGameRowId("92").build(), + manifest.toBuilder().setSourceGameTenantKey("game-design-tenant-92").build(), + manifest.toBuilder().setProvenanceKind("NEW_GAME_ROW").build(), + manifest.toBuilder().setGameSessionEvidenceDigest("sha256:" + "b".repeat(64)).build()); + + for (GameSessionTenantAssociationManifestEvidence changed : changedManifests) { + assertAssociationRejected(valid.toBuilder().setManifest(changed).build(), "manifest digest"); + } + assertAssociationRejected( + valid.toBuilder().setManifest(manifest.toBuilder().setSchemaVersion(2).build()).build(), + "manifest is invalid"); + } + + @Test + void retainedAssociationRejectsChangedEchoAndRecomputedForeignRequestBindings() throws Exception { + ResolveLegacyGameSessionTenantAssociationResponse valid = associationResponse(); + assertAssociationRejected( + valid.toBuilder().setRequestId(SOURCE_OPERATION_ID.toString()).build(), + "exact request echo"); + + List foreignEvidence = + List.of( + associationEvidenceWith( + REQUEST_ID.toString(), NAMESPACE, LEGACY_GAME_SESSION_TENANT_ID, TENANT_ID), + associationEvidenceWith( + SOURCE_OPERATION_ID.toString(), "other", LEGACY_GAME_SESSION_TENANT_ID, TENANT_ID), + associationEvidenceWith(SOURCE_OPERATION_ID.toString(), NAMESPACE, "24", TENANT_ID), + associationEvidenceWith( + SOURCE_OPERATION_ID.toString(), + NAMESPACE, + LEGACY_GAME_SESSION_TENANT_ID, + REQUEST_ID)); + for (GameSessionTenantAssociationEvidence evidence : foreignEvidence) { + assertAssociationRejected(associationResponse(evidence), "exact request"); + } + } + + @Test + void retainedAssociationRejectsInvalidSignatureAndDigestAndPropagatesUnavailable() + throws Exception { + ResolveLegacyGameSessionTenantAssociationResponse valid = associationResponse(); + assertAssociationRejected( + valid.toBuilder().setEd25519Signature("not-base64").build(), "signature is invalid"); + assertAssociationRejected( + valid.toBuilder() + .setEd25519Signature( + SIGNATURE_SHAPE_FIXTURE.substring(0, SIGNATURE_SHAPE_FIXTURE.length() - 2)) + .build(), + "signature is not canonical"); + assertAssociationRejected( + valid.toBuilder() + .setEd25519Signature(Base64.getEncoder().encodeToString(new byte[63])) + .build(), + "signature is not canonical"); + assertAssociationRejected( + valid.toBuilder().setManifestDigest("sha256:" + "0".repeat(64)).build(), "manifest digest"); + + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + StatusRuntimeException unavailable = + Status.UNAVAILABLE.withDescription("Game Design owner unavailable").asRuntimeException(); + when(stub.resolveLegacyGameSessionTenantAssociation(any())).thenThrow(unavailable); + GameDesignRuntimeTenantIdentityClient client = newClient(stub); + assertThatThrownBy( + () -> + client.resolveLegacyGameSessionTenantAssociation( + TENANT_ID.toString(), + SOURCE_OPERATION_ID.toString(), + LEGACY_GAME_SESSION_TENANT_ID, + REQUEST_ID.toString())) + .isSameAs(unavailable); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void retainedAssociationRejectsUseBeforeClientInitialization() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignRuntimeTenantIdentityClient client = newClientWithoutStub(channelFactory); + assertThatThrownBy( + () -> + client.resolveLegacyGameSessionTenantAssociation( + TENANT_ID.toString(), + SOURCE_OPERATION_ID.toString(), + LEGACY_GAME_SESSION_TENANT_ID, + REQUEST_ID.toString())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + verifyNoInteractions(channelFactory); + } + private static ResolveAuthoredWorldSourceResponse authoredResponse() { return authoredResponse(NAMESPACE, TENANT_ID, SOURCE_OPERATION_ID, "world-one"); } @@ -224,6 +476,76 @@ private static ResolveAuthoredWorldSourceResponse authoredResponse( .build(); } + private static GameSessionTenantAssociationEvidence associationEvidence() { + return associationEvidenceWith( + SOURCE_OPERATION_ID.toString(), NAMESPACE, LEGACY_GAME_SESSION_TENANT_ID, TENANT_ID); + } + + private static GameSessionTenantAssociationEvidence associationEvidenceWith( + String operationId, String namespace, String retainedTenantKey, UUID canonicalTenantId) { + return new GameSessionTenantAssociationEvidence( + 1, + UUID.fromString(operationId), + namespace, + "owner-key-1", + "owner@example.test", + "approval-2026-09", + "2026-09-30T12:00:00Z", + retainedTenantKey, + canonicalTenantId, + "91", + SOURCE_KEY, + "RETAINED_GAME_V30", + ASSOCIATION_SOURCE_DIGEST); + } + + private static ResolveLegacyGameSessionTenantAssociationResponse associationResponse() { + return associationResponse(associationEvidence()); + } + + private static ResolveLegacyGameSessionTenantAssociationResponse associationResponse( + GameSessionTenantAssociationEvidence evidence) { + GameSessionTenantAssociationManifestEvidence manifest = + GameSessionTenantAssociationManifestEvidence.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setOperationId(evidence.operationId().toString()) + .setTargetNamespace(evidence.targetNamespace()) + .setSignerKeyId(evidence.signerKeyId()) + .setApprovedBy(evidence.approvedBy()) + .setApprovalReference(evidence.approvalReference()) + .setSignedAt(evidence.signedAt()) + .setLegacyGameSessionTenantId(evidence.legacyGameSessionTenantId()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setSourceGameRowId(evidence.sourceGameRowId()) + .setSourceGameTenantKey(evidence.sourceGameTenantKey()) + .setProvenanceKind(evidence.provenanceKind()) + .setGameSessionEvidenceDigest(evidence.gameSessionEvidenceDigest()) + .build(); + return ResolveLegacyGameSessionTenantAssociationResponse.newBuilder() + .setRequestId(REQUEST_ID.toString()) + .setManifest(manifest) + .setManifestDigest(evidence.manifestDigest()) + .setEd25519Signature(SIGNATURE_SHAPE_FIXTURE) + .build(); + } + + private static void assertAssociationRejected( + ResolveLegacyGameSessionTenantAssociationResponse response, String message) throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + when(stub.resolveLegacyGameSessionTenantAssociation(any())).thenReturn(response); + GameDesignRuntimeTenantIdentityClient client = newClient(stub); + + assertThatThrownBy( + () -> + client.resolveLegacyGameSessionTenantAssociation( + TENANT_ID.toString(), + SOURCE_OPERATION_ID.toString(), + LEGACY_GAME_SESSION_TENANT_ID, + REQUEST_ID.toString())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(message); + } + @Test void exactOwnerResponseIsTypedAndStableOnRetryForBothProvenanceKinds() throws Exception { TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); From 2e37b38f5fc022844f97ce654e4678771c620376 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 00:53:23 +1300 Subject: [PATCH 05/23] feat(unit1b): persist fenced retained Game Session tenant associations --- .github/workflows/ci.yml | 20 + .../game-design-service/api-contracts.md | 2 +- .../game-session-service/api-contracts.md | 21 + .../game-session-service/runtime-and-data.md | 2 +- .../player-access-and-session.md | 12 +- ...onRetainedTenantAssociationRepository.java | 530 +++++++++++++++ .../GameSessionRetainedTenantSnapshot.java | 528 +++++++++++++++ ...ssionRetainedTenantSnapshotRepository.java | 306 +++++++++ ...ssionRetainedTenantAssociationService.java | 186 ++++++ .../V8__retained_tenant_association.sql | 105 +++ ...tAssociationRepositoryIntegrationTest.java | 606 ++++++++++++++++++ ...nantSnapshotRepositoryIntegrationTest.java | 513 +++++++++++++++ ...GameSessionRetainedTenantSnapshotTest.java | 213 ++++++ ...nRetainedTenantAssociationServiceTest.java | 260 ++++++++ 14 files changed, 3300 insertions(+), 4 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationService.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V8__retained_tenant_association.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationServiceTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ad5d586254..ef611ff759 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -968,6 +968,26 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepositoryIntegrationTest#concurrentExactIntakeRetriesReturnOneReceiptAndSlugRaceHasOneWinner()' \ game-session-service + - name: Run Game Session retained tenant snapshot and association PostgreSQL component proof + if: ${{ matrix.module == 'game-session-service' }} + run: | + ./gradlew :game-session-service:integrationTest \ + --tests integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepositoryIntegrationTest \ + --tests integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepositoryIntegrationTest \ + --require-suite integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepositoryIntegrationTest#capturesExactOrderedTenantProjectionAndStableDigestUnderReadCommittedOwnerTransaction()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepositoryIntegrationTest#captureUsesNowaitToRejectAnExistingWriterThenSucceedsAfterRollback()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepositoryIntegrationTest#shareFenceBlocksConcurrentInsertUpdateDeleteAcrossEverySourceFamilyAndReleasesAfterCommitOrRollback()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#exactRetryReturnsHistoricalReceiptWithoutRecapturingChangedSource()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#lostAcknowledgementExactRetryReturnsSameOriginalOperationAndBytesWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#rollbackLeavesNoAssociationClaimAndNewAttemptSucceeds()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#concurrentExactFirstWritersReturnSameImmutableReceipt()' \ + game-session-service + - name: 🧪 Run Gradle Checks id: checks run: | diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 30ff4d904b..7c3d22df77 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -52,7 +52,7 @@ Game Design atomically claims the operation and stores the complete signed evide The committed Game Design read validates the stored closed manifest, canonical signature shape, digest, exact scope and persisted source. It does not reauthorize the historical approval against a mutable public-key allowlist; signature authorization occurs before the immutable owner commit and again for a submitted exact retry. Read access still requires the concrete Game Session peer. -The `gameSessionEvidenceDigest` names Game Session's separately captured retained-row evidence. Before first local association commit, Game Session must verify that exact evidence against its own retained catalog/runtime rows under its owner fence, then store and read back the immutable association and source evidence together. Changed, missing, extra or contradictory captured rows deny that first commit. An exact retry returns the original committed association, not a newly inferred mapping; later catalog state changes do not rewrite the original approval. The concrete retained-row snapshot schema and producer/receiver database proof remain required before this path is wired. This receipt establishes tenant identity only, never current membership, entitlement, lifecycle, pointer or gameplay admission. +The `gameSessionEvidenceDigest` names Game Session's separately captured retained-row evidence. The [Game Session snapshot and local association contract](../game-session-service/api-contracts.md#retained-tenant-identity-snapshot-and-local-association) owns its closed projection, transaction fence, local operation/digests and immutable receiver readback. Changed, missing, extra or contradictory captured rows deny first local commit; exact retry returns the original association, not a newly inferred mapping. Producer/receiver database and live authentication proof remain required before this path is wired. This receipt establishes tenant identity only, never current membership, entitlement, lifecycle, pointer or gameplay admission. **Implementation and activation boundary:** The manifest and verification contract is a prerequisite for the separately tracked owner persistence, authenticated readback and retained-row consumer. No retained mapping, catalog enrollment, public creation route, credential path or membership RPC is enabled by specifying or locally validating it. Live approval custody and materialization, database concurrency/readback, receiver evidence and authenticated negative-call proof remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 15e0761749..db610f8ad2 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -46,6 +46,27 @@ The owner transaction atomically persists the local non-nil UUID operation, immu This source intake records no numeric tenant alias, instance, realm, pointer, lease, membership, authority generation or admission. It does not attach a retained Game Session runtime row: that requires the separately audited association and exact retained-row proof. The normal authorized creation workflow may invoke intake automatically after its Game Design commit; the primitive is not a public creator API and cannot bypass Account-owned creator/terms authorization. Source receipts and selector claims remain immutable survivor evidence; cleanup or release requires its owner retention proof rather than an invented TTL. Runtime catalog and credential activation stay denied until their complete producer, consumer and live proof gates pass. +### Retained tenant identity snapshot and local association + +Game Session owns the evidence behind `gameSessionEvidenceDigest` in [Game Design's audited association](../game-design-service/api-contracts.md#audited-retained-game-session-tenant-association). It captures an exact, declared identity projection of its retained rows, not a complete runtime backup or proof of historical lifecycle, effects or admission. The closed version-1 snapshot contains `schemaVersion=1`, the exact `targetNamespace`, canonical positive BIGINT decimal-string `legacyGameSessionTenantId`, and all six arrays below. Each array includes every row for that tenant, in ascending numeric primary-key order; the shared namespace uses its tenant primary key. Row objects contain exactly their listed SQL field names. SQL integer values are canonical decimal strings, UUIDs are canonical lowercase strings, booleans are JSON booleans, text is exact valid Unicode, and absent nullable fields are explicit JSON null. No timestamp, display label, actor/reason or participant-result payload is reconstructed or asserted by this projection. + +| Snapshot array / source table | Exact projected fields | +| --- | --- | +| `instances` / `game_instances` | `id`, `tenant_id`, `runtime_version`, `script_patch_version`, `owner_account_id`, `status`, `row_version`, `game_template_id`, `launch_descriptor_id`, `version_id`, `release_bundle_id`, `version_state_epoch`, `generation_config_revision`, `remap_set_id`, `script_patch_pinned_control_plane_request_id`, `script_pin_epoch` | +| `pointers` / `gameplay_admission_pointer` | `id`, `tenant_id`, `game_instance_id`, `world_slug`, `realm_slug`, `pointer_version`, `catalog_revision`, `visible`, `requires_character_selection`, `state_scope`, `character_creation_policy`, `public_production_realm`, `realm_id`, `playable_state_namespace_id` | +| `sharedNamespaces` / `gameplay_tenant_shared_playable_state_namespace` | `tenant_id`, `playable_state_namespace_id` | +| `backfillIssues` / `gameplay_admission_pointer_identity_backfill_issue` | Must be empty; any matching unresolved issue denies capture | +| `pointerEvents` / `gameplay_admission_pointer_event` | `id`, `tenant_id`, `game_instance_id`, `world_slug`, `realm_slug`, `pointer_version`, `visible`, `requires_character_selection`, `state_scope`, `character_creation_policy`, `control_plane_request_id`, `prepared_version_upgrade_id`, `public_production_realm` | +| `preparedUpgrades` / `prepared_version_upgrade` | `id`, `tenant_id`, `preparation_id`, `control_plane_request_id`, `source_game_instance_id`, `source_version_id`, `target_version_id`, `target_launch_descriptor_id`, `remap_set_id`, `result`, `executed_target_game_instance_id`, `executed_pointer_version`, `execution_control_plane_request_id` | + +The owner encodes this closed object using RFC 8785 canonical JSON. The SHA-256 preimage consists of two UTF-8 segments, the exact domain `game-session/retained-tenant-identity-snapshot/v1` and that canonical JSON, each prefixed by its decimal UTF-8 byte length and a colon. The digest is lowercase `sha256:` plus 64 hexadecimal digits. Unknown fields, noncanonical values, duplicate or out-of-order rows, changed scope or digest, and empty retained evidence deny use. Every current pointer must refer to a captured instance of that same tenant, have complete realm/namespace UUIDs and an exact `SHARED` or `ISOLATED` scope; a SHARED pointer must match the captured tenant-shared namespace. Historical pointer events can survive their former runtime instance; they do not acquire missing realm, namespace, catalog revision or World lifecycle evidence through this capture. + +Capture requires a non-read-only Game Session owner transaction at PostgreSQL READ COMMITTED. Before any source read it acquires one fixed-order `SHARE MODE NOWAIT` relation-lock statement for all six source tables. Those locks prevent concurrent insertion, mutation, deletion and truncation, including empty-range phantom inserts, and remain held through the local association commit or rollback. Ordinary reads remain possible. An existing writer causes immediate retryable capture failure, not a durable terminal receipt or an assertion of absence. This short, global source-write barrier is limited to the one-time retained-data association; it is not a per-request gameplay lock or an automated runtime quiescence policy. Operational and live use remain gated until the complete capture/receiver proof passes. A prior unlocked preview may prepare approval evidence, but only the receiver's fenced recapture can authorize first commit. + +The local receiver authenticates and validates the exact Game Design receipt before entering the source-lock transaction; no source locks are held across a network call. It then recaptures the declared projection and requires its exact namespace, retained key and digest to match the approval. It atomically stores the complete immutable approval, snapshot and local operation with namespace-qualified one-to-one canonical UUID and retained-key claims, and reads back that exact result before returning. Changed input under the same operation or a conflicting claim denies without partial state. Exact retry and committed readback return the original evidence without recapturing or rewriting later source state; they are historical association proof only. Missing or contradictory readback remains unavailable. This owner-local primitive does not create a realm, pointer, lease, membership, grant or credential, and cannot activate a catalog or gameplay path. + +The local stable non-nil UUID `associationRequestId` is distinct from Game Design's approval `operationId` and the transient authenticated read attempt. Its request digest frames the domain `game-session/retained-tenant-association-request/v1`, exact namespace, local request UUID, complete Game Design manifest digest and exact canonical signature, in that order. The local receipt digest frames `game-session/retained-tenant-association-receipt/v1`, the persisted non-nil local operation UUID, request digest, approval manifest digest and snapshot evidence digest. Both use the same UTF-8 byte-length framing and lowercase SHA-256 rendering above. Committed readback requires the exact local operation, request, namespace, canonical tenant UUID and retained key, and validates the complete stored approval and snapshot before returning; a transient read echo is never stored as either owner operation. + The World Management database row and monotonic lifecycle epoch are the admission authority under [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). Game Session reads that owner state and epoch at lifecycle-sensitive boundaries; it does not use Temporal workflow status, worker memory, or a projection to admit an instance. `PREPARING` is non-admissible, `ACTIVE` is admissible only after the final version-state and owner checks, `FAILED_PRE_ACTIVATION` is terminal for admission, `TERMINATING` rejects new and reconnected bindings, and `TERMINATED` remains closed. Multi-Tenancy owns the realm catalog, the canonical durable `{tenantId, realmId}` pointer identity and its routing/admission semantics, while Game Session is the sole runtime resolver, persister, and compare-and-set orchestrator for that resolved catalog and admission-pointer state; neither service owns World lifecycle state. Replacement preparation and pointer swap carry the catalog-bound `worldSlug`/`realmSlug` selectors, stable `playableStateNamespaceId`/`playableStateScope`, and, for private/playtest targets, the canonical lifecycle proof tuple `{playtestLifecycleId, playtestStateGeneration}` from [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); changing `gameInstanceId` does not authorize a new realm identity, namespace, or durable-state copy. Cutover remains closed unless every owner reports fresh compatible state and the fenced pointer CAS succeeds. After a source swap, Game Session drains and closes source bindings, then asks World to progress termination; it reports a stopped runtime only after authoritative `TERMINATED` readback. Public-production requests omit both playtest fields and reject supplied values. 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 d2d4366ff0..3101d7fb64 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -40,7 +40,7 @@ The sections below define the target-state runtime contract. Current implementat - Bounded durable semantic reconnect-context persistence is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, and a fresh first-party `PLAY` no longer replays an old buffer solely because a connect token exists. Namespace-key migration to `{tenantId, playableStateNamespaceId, characterId}`, the distinct durable `resumeContextGeneration` episode fence and termination protocol, complete-envelope hard-bound accounting and omission-marker convergence, and cross-transport/race proof of post-logout suppression remain gaps. - Current live/recent presence projection wiring is implementation drift: `gameplaypresence:session:`, its game-instance/account set indexes, and `accountrecentpresence::` are written with untagged, separate Redis value/index operations. Game Session remains the target owner, but the physical shapes, storage-role classification, exact scope, partial-write handling, reset/rebuild/readback behavior, and private-by-failure contract are unproved; the [Redis owner and reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) records these current families without accepting them as target authority. - Current LOOK handling writes the legacy `lookcache::` projection even though reads remain authoritative/uncached. Its ten-minute, session-or-instance-only scope lacks the target viewer, policy, and causal read-fence identity; it is disposable implementation drift and must not be treated as the target `view:room-look:*` cache. See the [Redis cache catalog](../../system-architecture-redis-cache-reference.md#cache-rate-limit-key-catalog). -- The current Flyway history also contains the Java/nontransactional `V8__remote_followup_target_instance_effect_identity` migration (`CREATE INDEX CONCURRENTLY`, `canExecuteInTransaction() = false`). This is outside the SQL migration input used by shared jOOQ generation and is not yet inventoried or proved as a narrow exception to the SQL-only persistence lineage. +- The remote-followup target-instance uniqueness index `idx_remote_followup_target_instance_region_epoch_effect` is defined in the SQL V1 baseline, not a separate Java/nontransactional migration. Retained-data upgrade and fresh-start proof remain separately tracked at their owning runtime boundary. ## Runtime Details 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 43a5f2f06f..af794bf8f7 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,15 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -2026-10-01 the #2923 candidate adds the distinct Game Design owner-approved retained Game Session tenant association prerequisite: a closed shared manifest and UTF-8-framed digest, purpose-specific Ed25519 approval verification, V34 immutable one-to-one owner storage, and exact Game Session-only readback. The unwired Game Session client validates the complete echoed manifest and exact request scope over its existing verified Game Design channel. Default and production bearer-bypass lists retain the same exact protected owner reads; their handlers still require the concrete same-namespace peer before owner access. This does not install a local Game Session mapping or prove its retained rows. Protected approval custody/import, the owner-fenced retained-row snapshot and receiver commit/readback, fresh-image and live authentication proof, and catalog/admission activation remain open. The canonical source contract is [Game Design's audited retained association](../../architecture/microservices/game-design-service/api-contracts.md#audited-retained-game-session-tenant-association); Game Session's API records only its consumer consequence. +2026-10-02 #2923 adds the unwired Game Session owner-local receiver for the separately audited Game Design tenant association. Its closed retained identity snapshot captures all six declared source families under one short READ COMMITTED write fence, rejects incomplete pointers/backfill issues and changed source evidence, and binds the exact namespace, retained key and canonical tenant UUID. The service obtains authenticated Game Design evidence before opening that transaction; V8 then stores the complete immutable approval, snapshot, namespace-qualified one-to-one claims and exact local request/result. Lost-response recovery and exact retry return the original durable evidence without recapturing or rewriting later source state. Neither the service nor association repository is registered as a runtime bean or public route. The canonical contract is [Game Session's retained snapshot and association](../../architecture/microservices/game-session-service/api-contracts.md#retained-tenant-identity-snapshot-and-local-association). + +Local Game Session full check/JAR, Java formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown passed: 123 tasks, 33 executed/90 up-to-date. Tests executed 1,747 unit cases, 18 non-PostgreSQL integration cases and one cross-service case with zero failures/errors; the nine new snapshot/service unit cases all executed. Seventeen unit, 128 integration and 33 cross-service cases skipped. The 12 new PostgreSQL cases (three snapshot-fence and nine association cases) compiled/discovered but all skipped without Docker, so source-lock, phantom exclusion, concurrent first-writer, immutable readback and rollback database behavior remain unproved on this candidate. Initial delegated import/jOOQ API compile defects and an unnecessary analyzer suppression were corrected without relaxing any assertion or transaction guard. The new early strict CI gate requires both suites and their mandatory methods before the broader check; workflow presence is not execution proof. Protected approval custody/import, live authenticated handoff, canonical catalog/carrier convergence and all runtime activation remain open. + +Exact source/read candidate `2583d65671bb8f9256b1216e5cbee5fe50c3d9ff` [CI36850617996](https://github.com/benhook1013/FireMUD/actions/runs/36850617996) completed FAILURE, but its new mandatory Game Design association suite executed all nine PostgreSQL cases with zero skips/failures/errors; each of four required methods executed once and passed. Strict Game Design creation8/authored-source10, Game Session intake5 and Account JOIN/LEFT39, exchange9, issuance9, authority-generation2, outbox4, committed-source18, fresh association6, pair8 and fresh UUID snapshot11 also passed without skips/failures/errors. Counts come from the strict runner report verifier; downloaded test artifacts are HTML, not raw JUnit XML. Game Session's broader check was cancelled after intake, so no broader Script Pin/WebSocket execution is credited. These component proofs do not enable the receiver, catalog, membership RPC or credentials. + +The same run failed tooling's Game Design recovery-warning summary contract, Python Ruff B023 for an unbound `failure` loop variable, Automation formatting in `NpcFormationGrpcServiceTest`, Game Design's separately routed EntityDigest duplicate9301 fixture (one integration failure among48), and TCP cross-service13/17 with explicit `ERROR AUTH_UNAVAILABLE` gameplay admission responses. The Automation job produced no test report, so this run does not reproduce or prove its earlier PostgreSQL failures. Bounded remote lineage inspection instead located those earlier null-base upsert/compensation corrections in already-merged #2829 (`a18315a1e15c74775ffdec2e782563af668598bc` and later fixture refinements); this stale candidate lacks that ancestry and must not invent a duplicate fix. General's current #2872 still contains the Game Design duplicate fixture; its existing two target-PR routes remain the handoff. Complete canonical UUID catalog/carrier and authorization implementation remain required for the real TCP admission failures; denial is containment, not positive implementation proof. + +2026-10-01 published #2923 head `2583d6567` added the distinct Game Design owner-approved retained Game Session tenant association prerequisite: a closed shared manifest and UTF-8-framed digest, purpose-specific Ed25519 approval verification, V34 immutable one-to-one owner storage, and exact Game Session-only readback. The unwired Game Session client validates the complete echoed manifest and exact request scope over its existing verified Game Design channel. Default and production bearer-bypass lists retain the same exact protected owner reads; their handlers still require the concrete same-namespace peer before owner access. That exact historical source/read checkpoint did not install a local Game Session mapping or prove its retained rows; the receiver candidate and remaining proof gates are recorded above. The canonical source contract is [Game Design's audited retained association](../../architecture/microservices/game-design-service/api-contracts.md#audited-retained-game-session-tenant-association); Game Session's API records its consumer consequence and owns the local snapshot/association contract. The new prerequisite passed local shared-core and Game Design/Game Session full checks, formatting, Checkstyle, SpotBugs, JaCoCo and both service JARs. Shared-core 127 and Game Design 313 unit cases executed with zero skips/failures/errors; Game Session executed 1,738 unit cases, 18 non-PostgreSQL integration cases and one cross-service case without failures/errors. Game Session skipped 17 unit, 116 integration and 33 cross-service cases; all 48 Game Design PostgreSQL cases, including the nine new association cases, compiled/discovered but skipped without Docker. The required new PostgreSQL task and strict method/suite verifier precede the longer Game Design check in CI; their presence is not execution evidence. Local fixture accessor/import and module-resource selection defects were corrected before the passing owner gate. No required assertion, UUID guard or lifecycle boundary was weakened. The composed shared-core/Game Design/Game Session check and packaging gate, links/Markdown and Flyway sanity (12 sets/125 files) passed: 167 tasks, 21 executed/146 up-to-date. Test tasks in that final gate were up-to-date from the preceding same-code executions, not new executions. Actionlint, all 23 CI-scope contracts and diff hygiene also passed. Exact corrected-candidate runner execution and live owner/consumer proof remain required. @@ -16,7 +24,7 @@ The Game Session tenant-source client and authored-world intake consumer, V7 sch The owner-local LEFT candidate passed the consolidated Account/Game Session full checks, affected Java formatting, both service JARs, Checkstyle, SpotBugs, JaCoCo, links, Markdown and Flyway sanity (12 sets/124 files): 153 tasks, 21 executed/132 up-to-date. Account's 469 unit cases and Game Session's 1,731 unit cases executed successfully in the preceding same-code gates; unchanged unit tasks were up-to-date in the final gate. Game Session also executed 18 non-PostgreSQL integration cases and one cross-service case; 17 unit, 116 integration and 33 cross-service cases skipped. All 145 Account PostgreSQL cases, including the expanded 38-case JOIN/LEFT suite and seven required LEFT methods, compiled/discovered but skipped without Docker. Actionlint, all 23 CI-scope contracts and diff hygiene passed. Mocked INACTIVE consumer negatives preserve the production lifecycle guard and distinguish unbound denial from cleanup of an existing binding. Exact-candidate PostgreSQL execution, fresh-image startup and authenticated end-to-end producer/consumer proof remain required; no runtime path is enabled. -Exact child head `32fe02cbb342365863b83252c91e26d39173abc3` [CI36844382190](https://github.com/benhook1013/FireMUD/actions/runs/36844382190) completed FAILURE. The strict runner HTML verifier passed Account JOIN/LEFT39/39 with zero skips, failures or errors, including all seven LEFT cases and the new stored-audit readback. Strict exchange9, connect9, source/history18, fresh association6, pair8 and fresh UUID snapshot11 also passed; Game Design creation8/authored-source10 and Game Session intake5 passed strict. The aggregate remained red: Python Ruff10; a dev-demo summary validator reported an unsupported step with a warning; Automation PostgreSQL8/69 failed; Game Design's broader EntityDigest fixture had one duplicate-key failure among39; TCP Proxy cross-service had13 failures among17; and Game Session's broader check was cancelled after17 CommunicationWebSocket failures. These aggregate failures are not attributed as inherited or flaky. This evidence belongs only to committed child head `32fe02c`; the dirty new Game Design/Game Session association manifest/store/read package in this worktree is uncommitted and has no executed database, receiver, or activation proof. No live readiness or runtime activation is established. +Exact child head `32fe02cbb342365863b83252c91e26d39173abc3` [CI36844382190](https://github.com/benhook1013/FireMUD/actions/runs/36844382190) completed FAILURE. The strict runner HTML verifier passed Account JOIN/LEFT39/39 with zero skips, failures or errors, including all seven LEFT cases and the new stored-audit readback. Strict exchange9, connect9, source/history18, fresh association6, pair8 and fresh UUID snapshot11 also passed; Game Design creation8/authored-source10 and Game Session intake5 passed strict. The aggregate remained red: Python Ruff10; a dev-demo summary validator reported an unsupported step with a warning; Automation PostgreSQL8/69 failed; Game Design's broader EntityDigest fixture had one duplicate-key failure among39; TCP Proxy cross-service had13 failures among17; and Game Session's broader check was cancelled after17 CommunicationWebSocket failures. These aggregate failures require separate ownership and ancestry adjudication rather than a blanket inherited/flaky label. This evidence belongs only to committed child head `32fe02c`; the subsequent Game Design/Game Session association manifest/store/read package was published at `2583d6567` and is not proved by that earlier run. Its receiver and activation proof remain open. No live readiness or runtime activation is established. Exact parent `642d5d9f58d8e383c8614697f88f085ef3f56b39` [CI36835527324](https://github.com/benhook1013/FireMUD/actions/runs/36835527324) passed the strict five-case Game Session authored-world intake proof with zero skips/failures/errors. Account strict JOIN31, exchange9, issuance9, source/history18, association6, pair8, fresh UUID snapshot11 and generation2/outbox4, plus Game Design creation8/authored-source10, also passed without skips/failures/errors. These are runner-JUnit verifier results, not uploaded raw XML. Aggregate CI failed, with Game Session's broader check cancelled after 18 CommunicationWebSocket failures; Script Pin25 and focused WebSocket16 proof are not credited. This parent execution does not prove the new LEFT candidate or enable catalog, membership or credential paths. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java new file mode 100644 index 0000000000..c68a76c97e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepository.java @@ -0,0 +1,530 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient.LegacyGameSessionTenantAssociationReceipt; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unwired immutable local receipt for an approved association to retained Game Session rows. + * + *

The Game Design receipt is obtained by the service before the owner transaction begins. This + * repository only commits it after the local retained-row snapshot has been recaptured under its + * source fence. + */ +@SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Owner collaborators and namespace are validated before use; construction performs no" + + " database or network I/O and the caller explicitly owns local activation.") +public class GameSessionRetainedTenantAssociationRepository { + private static final int SCHEMA_VERSION = 1; + private static final int SIGNATURE_BYTES = 64; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String REQUEST_DOMAIN = + "game-session/retained-tenant-association-request/v1"; + private static final String RECEIPT_DOMAIN = + "game-session/retained-tenant-association-receipt/v1"; + + private static final Table ASSOCIATION = + DSL.table(DSL.name("game_session_retained_tenant_association")); + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field APPROVAL_SCHEMA_VERSION = + DSL.field(DSL.name("approval_schema_version"), Integer.class); + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field ASSOCIATION_REQUEST_ID = + DSL.field(DSL.name("association_request_id"), UUID.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field APPROVAL_OPERATION_ID = + DSL.field(DSL.name("approval_operation_id"), UUID.class); + private static final Field SIGNER_KEY_ID = + DSL.field(DSL.name("signer_key_id"), String.class); + private static final Field APPROVED_BY = DSL.field(DSL.name("approved_by"), String.class); + private static final Field APPROVAL_REFERENCE = + DSL.field(DSL.name("approval_reference"), String.class); + private static final Field SIGNED_AT = DSL.field(DSL.name("signed_at"), String.class); + private static final Field LEGACY_GAME_SESSION_TENANT_ID = + DSL.field(DSL.name("legacy_game_session_tenant_id"), Long.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field GAME_SESSION_EVIDENCE_DIGEST = + DSL.field(DSL.name("game_session_evidence_digest"), String.class); + private static final Field APPROVAL_MANIFEST_DIGEST = + DSL.field(DSL.name("approval_manifest_digest"), String.class); + private static final Field APPROVAL_SIGNATURE = + DSL.field(DSL.name("approval_signature"), String.class); + private static final Field SNAPSHOT_CANONICAL_JSON = + DSL.field(DSL.name("snapshot_canonical_json"), String.class); + private static final Field SNAPSHOT_EVIDENCE_DIGEST = + DSL.field(DSL.name("snapshot_evidence_digest"), String.class); + private static final Field RECEIPT_DIGEST = + DSL.field(DSL.name("receipt_digest"), String.class); + + private final DSLContext dsl; + private final GameSessionRetainedTenantSnapshotRepository snapshotRepository; + private final String workloadNamespace; + + public GameSessionRetainedTenantAssociationRepository( + DSLContext dsl, + GameSessionRetainedTenantSnapshotRepository snapshotRepository, + String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.snapshotRepository = + Objects.requireNonNull(snapshotRepository, "snapshotRepository must not be null"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + } + + /** + * Captures and commits one exact retained-tenant association under the caller's owner + * transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AssociationReceipt register( + UUID associationRequestId, LegacyGameSessionTenantAssociationReceipt sourceReceipt) { + requireWritableReadCommittedOwnerTransaction(); + requireNonNil(associationRequestId, "associationRequestId"); + ValidatedApproval approval = validateApproval(sourceReceipt); + GameSessionTenantAssociationEvidence evidence = approval.evidence(); + if (!workloadNamespace.equals(evidence.targetNamespace())) { + throw new InvalidAssociationEvidenceException( + "Game Design approval targets a different Game Session namespace"); + } + + String requestDigest = + requestDigest( + workloadNamespace, + associationRequestId, + approval.manifestDigest(), + approval.signature()); + Record existing = findByRequest(workloadNamespace, associationRequestId); + if (existing != null) { + return requireExactRetry(existing, associationRequestId, requestDigest, approval); + } + + GameSessionRetainedTenantSnapshot snapshot = + snapshotRepository.capture(workloadNamespace, evidence.legacyGameSessionTenantId()); + requireSnapshotMatchesApproval(snapshot, evidence); + + UUID localOperationId = UUID.randomUUID(); + String receiptDigest = + receiptDigest( + localOperationId, requestDigest, approval.manifestDigest(), snapshot.evidenceDigest()); + int inserted = + dsl.insertInto(ASSOCIATION) + .set(OPERATION_ID, localOperationId) + .set(APPROVAL_SCHEMA_VERSION, evidence.schemaVersion()) + .set(TARGET_NAMESPACE, workloadNamespace) + .set(ASSOCIATION_REQUEST_ID, associationRequestId) + .set(REQUEST_DIGEST, requestDigest) + .set(APPROVAL_OPERATION_ID, evidence.operationId()) + .set(SIGNER_KEY_ID, evidence.signerKeyId()) + .set(APPROVED_BY, evidence.approvedBy()) + .set(APPROVAL_REFERENCE, evidence.approvalReference()) + .set(SIGNED_AT, evidence.signedAt()) + .set(LEGACY_GAME_SESSION_TENANT_ID, evidence.legacyGameSessionTenantIdValue()) + .set(CANONICAL_TENANT_ID, evidence.canonicalTenantId()) + .set(SOURCE_GAME_ROW_ID, evidence.sourceGameRowIdValue()) + .set(SOURCE_GAME_TENANT_KEY, evidence.sourceGameTenantKey()) + .set(PROVENANCE_KIND, evidence.provenanceKind()) + .set(GAME_SESSION_EVIDENCE_DIGEST, evidence.gameSessionEvidenceDigest()) + .set(APPROVAL_MANIFEST_DIGEST, approval.manifestDigest()) + .set(APPROVAL_SIGNATURE, approval.signature()) + .set(SNAPSHOT_CANONICAL_JSON, snapshot.canonicalJson()) + .set(SNAPSHOT_EVIDENCE_DIGEST, snapshot.evidenceDigest()) + .set(RECEIPT_DIGEST, receiptDigest) + .onConflictDoNothing() + .execute(); + + Record byLocalOperation = findByOperationId(localOperationId); + if (byLocalOperation != null) { + AssociationReceipt stored = toValidatedReceipt(byLocalOperation); + requireExactInsertedReceipt(stored, associationRequestId, requestDigest, approval, snapshot); + return stored; + } + + Record racedRequest = findByRequest(workloadNamespace, associationRequestId); + if (racedRequest != null) { + return requireExactRetry(racedRequest, associationRequestId, requestDigest, approval); + } + if (inserted == 1) { + throw new InvalidAssociationEvidenceException( + "Committed retained-tenant association readback is missing"); + } + throw new AssociationConflictException( + "Canonical tenant or retained Game Session key is already associated"); + } + + /** Reads one exact committed association without source recapture, repair, or allocation. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read( + UUID localOperationId, + UUID associationRequestId, + UUID canonicalTenantId, + long legacyGameSessionTenantId, + String exactNamespace) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Retained-tenant association read requires a committed-outcome owner read"); + } + requireNonNil(localOperationId, "localOperationId"); + requireNonNil(associationRequestId, "associationRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requirePositive(legacyGameSessionTenantId, "legacyGameSessionTenantId"); + requireNamespace(exactNamespace); + if (!workloadNamespace.equals(exactNamespace)) { + throw new IllegalArgumentException( + "exactNamespace must match the configured Game Session workload namespace"); + } + + Record row = findByOperationId(localOperationId); + if (row != null) { + AssociationReceipt receipt = toValidatedReceipt(row); + if (!receipt.operationId().equals(localOperationId) + || !receipt.associationRequestId().equals(associationRequestId) + || !receipt.approval().canonicalTenantId().equals(canonicalTenantId) + || receipt.approval().legacyGameSessionTenantIdValue() != legacyGameSessionTenantId + || !receipt.approval().targetNamespace().equals(exactNamespace)) { + throw new InvalidAssociationEvidenceException( + "Retained-tenant association readback contradicts its exact identity request"); + } + return Optional.of(receipt); + } + + if (findByRequest(exactNamespace, associationRequestId) != null + || findByCanonicalTenant(exactNamespace, canonicalTenantId) != null + || findByLegacyKey(exactNamespace, legacyGameSessionTenantId) != null) { + throw new InvalidAssociationEvidenceException( + "Retained-tenant association exists under contradictory local identity"); + } + return Optional.empty(); + } + + private AssociationReceipt requireExactRetry( + Record row, + UUID associationRequestId, + String requestDigest, + ValidatedApproval expectedApproval) { + AssociationReceipt stored = toValidatedReceipt(row); + if (!stored.associationRequestId().equals(associationRequestId) + || !stored.requestDigest().equals(requestDigest) + || !stored.approval().equals(expectedApproval.evidence()) + || !stored.approvalManifestDigest().equals(expectedApproval.manifestDigest()) + || !stored.approvalSignature().equals(expectedApproval.signature())) { + throw new AssociationConflictException( + "Retained-tenant association request was reused with changed signed evidence"); + } + return stored; + } + + private void requireExactInsertedReceipt( + AssociationReceipt actual, + UUID associationRequestId, + String requestDigest, + ValidatedApproval approval, + GameSessionRetainedTenantSnapshot snapshot) { + if (!actual.associationRequestId().equals(associationRequestId) + || !actual.requestDigest().equals(requestDigest) + || !actual.approval().equals(approval.evidence()) + || !actual.approvalManifestDigest().equals(approval.manifestDigest()) + || !actual.approvalSignature().equals(approval.signature()) + || !actual.snapshot().equals(snapshot)) { + throw new InvalidAssociationEvidenceException( + "Committed retained-tenant association differs from its exact registration input"); + } + } + + private AssociationReceipt toValidatedReceipt(Record row) { + try { + UUID localOperationId = Objects.requireNonNull(row.get(OPERATION_ID)); + UUID associationRequestId = Objects.requireNonNull(row.get(ASSOCIATION_REQUEST_ID)); + String namespace = Objects.requireNonNull(row.get(TARGET_NAMESPACE)); + if (!Integer.valueOf(SCHEMA_VERSION).equals(row.get(APPROVAL_SCHEMA_VERSION))) { + throw new InvalidAssociationEvidenceException( + "Persisted retained-tenant association schema is unsupported"); + } + GameSessionTenantAssociationEvidence evidence = + new GameSessionTenantAssociationEvidence( + row.get(APPROVAL_SCHEMA_VERSION), + Objects.requireNonNull(row.get(APPROVAL_OPERATION_ID)), + namespace, + Objects.requireNonNull(row.get(SIGNER_KEY_ID)), + Objects.requireNonNull(row.get(APPROVED_BY)), + Objects.requireNonNull(row.get(APPROVAL_REFERENCE)), + Objects.requireNonNull(row.get(SIGNED_AT)), + Long.toString(Objects.requireNonNull(row.get(LEGACY_GAME_SESSION_TENANT_ID))), + Objects.requireNonNull(row.get(CANONICAL_TENANT_ID)), + Long.toString(Objects.requireNonNull(row.get(SOURCE_GAME_ROW_ID))), + Objects.requireNonNull(row.get(SOURCE_GAME_TENANT_KEY)), + Objects.requireNonNull(row.get(PROVENANCE_KIND)), + Objects.requireNonNull(row.get(GAME_SESSION_EVIDENCE_DIGEST))); + String manifestDigest = Objects.requireNonNull(row.get(APPROVAL_MANIFEST_DIGEST)); + String signature = Objects.requireNonNull(row.get(APPROVAL_SIGNATURE)); + requireSignatureShape(signature); + if (!evidence.manifestDigest().equals(manifestDigest)) { + throw new InvalidAssociationEvidenceException( + "Persisted retained-tenant approval digest does not match its closed manifest"); + } + + GameSessionRetainedTenantSnapshot snapshot = + new GameSessionRetainedTenantSnapshot( + namespace, + evidence.legacyGameSessionTenantId(), + Objects.requireNonNull(row.get(SNAPSHOT_CANONICAL_JSON)), + Objects.requireNonNull(row.get(SNAPSHOT_EVIDENCE_DIGEST))); + requireSnapshotMatchesApproval(snapshot, evidence); + + String requestDigest = Objects.requireNonNull(row.get(REQUEST_DIGEST)); + if (!requestDigest.equals( + requestDigest(namespace, associationRequestId, manifestDigest, signature))) { + throw new InvalidAssociationEvidenceException( + "Persisted retained-tenant association request digest is invalid"); + } + String receiptDigest = Objects.requireNonNull(row.get(RECEIPT_DIGEST)); + if (!receiptDigest.equals( + receiptDigest( + localOperationId, requestDigest, manifestDigest, snapshot.evidenceDigest()))) { + throw new InvalidAssociationEvidenceException( + "Persisted retained-tenant association receipt digest is invalid"); + } + requireNonNil(localOperationId, "localOperationId"); + requireNonNil(associationRequestId, "associationRequestId"); + return new AssociationReceipt( + localOperationId, + associationRequestId, + requestDigest, + evidence, + manifestDigest, + signature, + snapshot, + receiptDigest); + } catch (InvalidAssociationEvidenceException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidAssociationEvidenceException( + "Persisted retained-tenant association evidence is invalid", exception); + } + } + + private ValidatedApproval validateApproval( + LegacyGameSessionTenantAssociationReceipt sourceReceipt) { + if (sourceReceipt == null || sourceReceipt.evidence() == null) { + throw new InvalidAssociationEvidenceException("Game Design approval receipt is missing"); + } + GameSessionTenantAssociationEvidence source = sourceReceipt.evidence(); + GameSessionTenantAssociationEvidence evidence; + try { + evidence = + new GameSessionTenantAssociationEvidence( + source.schemaVersion(), + source.operationId(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.legacyGameSessionTenantId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.gameSessionEvidenceDigest()); + } catch (RuntimeException exception) { + throw new InvalidAssociationEvidenceException( + "Game Design approval manifest is invalid", exception); + } + String signature = sourceReceipt.ed25519Signature(); + requireSignatureShape(signature); + String manifestDigest = sourceReceipt.manifestDigest(); + if (manifestDigest == null || !evidence.manifestDigest().equals(manifestDigest)) { + throw new InvalidAssociationEvidenceException( + "Game Design approval digest does not match its closed manifest"); + } + return new ValidatedApproval(evidence, manifestDigest, signature); + } + + private void requireSnapshotMatchesApproval( + GameSessionRetainedTenantSnapshot snapshot, GameSessionTenantAssociationEvidence evidence) { + if (snapshot == null + || !workloadNamespace.equals(snapshot.targetNamespace()) + || !evidence.legacyGameSessionTenantId().equals(snapshot.legacyGameSessionTenantId()) + || !evidence.gameSessionEvidenceDigest().equals(snapshot.evidenceDigest())) { + throw new InvalidAssociationEvidenceException( + "Retained Game Session snapshot does not match the approved owner evidence"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Retained-tenant association registration requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Retained-tenant association registration requires a writable owner transaction"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS transaction_isolation, " + + "current_setting('transaction_read_only') AS transaction_read_only"); + if (settings == null + || !"read committed".equals(settings.get("transaction_isolation", String.class)) + || !"off".equals(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "Retained-tenant association registration requires writable READ COMMITTED"); + } + } + + private Record findByOperationId(UUID operationId) { + return dsl.selectFrom(ASSOCIATION) + .where(OPERATION_ID.eq(operationId).and(TARGET_NAMESPACE.eq(workloadNamespace))) + .fetchOne(); + } + + private Record findByRequest(String namespace, UUID requestId) { + return dsl.selectFrom(ASSOCIATION) + .where(TARGET_NAMESPACE.eq(namespace).and(ASSOCIATION_REQUEST_ID.eq(requestId))) + .fetchOne(); + } + + private Record findByCanonicalTenant(String namespace, UUID tenantId) { + return dsl.selectFrom(ASSOCIATION) + .where(TARGET_NAMESPACE.eq(namespace).and(CANONICAL_TENANT_ID.eq(tenantId))) + .fetchOne(); + } + + private Record findByLegacyKey(String namespace, long legacyKey) { + return dsl.selectFrom(ASSOCIATION) + .where(TARGET_NAMESPACE.eq(namespace).and(LEGACY_GAME_SESSION_TENANT_ID.eq(legacyKey))) + .fetchOne(); + } + + private static String requestDigest( + String exactNamespace, UUID associationRequestId, String manifestDigest, String signature) { + return framedDigest( + REQUEST_DOMAIN, exactNamespace, associationRequestId.toString(), manifestDigest, signature); + } + + private static String receiptDigest( + UUID localOperationId, + String requestDigest, + String manifestDigest, + String snapshotEvidenceDigest) { + return framedDigest( + RECEIPT_DOMAIN, + localOperationId.toString(), + requestDigest, + manifestDigest, + snapshotEvidenceDigest); + } + + private static String framedDigest(String... segments) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String segment : segments) { + byte[] bytes = segment.getBytes(StandardCharsets.UTF_8); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(output.toByteArray())); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void requireSignatureShape(String signature) { + if (signature == null) { + throw new InvalidAssociationEvidenceException("Game Design approval signature is missing"); + } + final byte[] bytes; + try { + bytes = Base64.getDecoder().decode(signature); + } catch (IllegalArgumentException exception) { + throw new InvalidAssociationEvidenceException( + "Game Design approval signature is not canonical Ed25519 base64", exception); + } + if (bytes.length != SIGNATURE_BYTES + || !Base64.getEncoder().encodeToString(bytes).equals(signature)) { + throw new InvalidAssociationEvidenceException( + "Game Design approval signature is not canonical 64-byte Ed25519 base64"); + } + } + + private static void requireNamespace(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("exactNamespace must be one canonical DNS label"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0) { + throw new IllegalArgumentException(label + " must be a positive BIGINT"); + } + } + + private record ValidatedApproval( + GameSessionTenantAssociationEvidence evidence, String manifestDigest, String signature) {} + + /** Complete immutable local evidence; it contains no credential or approval private key. */ + public record AssociationReceipt( + UUID operationId, + UUID associationRequestId, + String requestDigest, + GameSessionTenantAssociationEvidence approval, + String approvalManifestDigest, + String approvalSignature, + GameSessionRetainedTenantSnapshot snapshot, + String receiptDigest) {} + + public static class AssociationConflictException extends RuntimeException { + public AssociationConflictException(String message) { + super(message); + } + } + + public static class InvalidAssociationEvidenceException extends RuntimeException { + public InvalidAssociationEvidenceException(String message) { + super(message); + } + + public InvalidAssociationEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java new file mode 100644 index 0000000000..3ea095fe83 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java @@ -0,0 +1,528 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Iterator; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Closed, immutable evidence for Game Session's retained-tenant identity projection. */ +public record GameSessionRetainedTenantSnapshot( + String targetNamespace, + String legacyGameSessionTenantId, + String canonicalJson, + String evidenceDigest) { + private static final String DIGEST_DOMAIN = "game-session/retained-tenant-identity-snapshot/v1"; + private static final Pattern CANONICAL_DECIMAL = + Pattern.compile("(?:0|[1-9][0-9]*|-[1-9][0-9]*)"); + private static final Pattern CANONICAL_UUID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final BigInteger LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE); + private static final BigInteger LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + private static final Set ENVELOPE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "legacyGameSessionTenantId", + "instances", + "pointers", + "sharedNamespaces", + "backfillIssues", + "pointerEvents", + "preparedUpgrades"); + private static final Set INSTANCE_FIELDS = + Set.of( + "id", + "tenant_id", + "runtime_version", + "script_patch_version", + "owner_account_id", + "status", + "row_version", + "game_template_id", + "launch_descriptor_id", + "version_id", + "release_bundle_id", + "version_state_epoch", + "generation_config_revision", + "remap_set_id", + "script_patch_pinned_control_plane_request_id", + "script_pin_epoch"); + private static final Set POINTER_FIELDS = + Set.of( + "id", + "tenant_id", + "game_instance_id", + "world_slug", + "realm_slug", + "pointer_version", + "catalog_revision", + "visible", + "requires_character_selection", + "state_scope", + "character_creation_policy", + "public_production_realm", + "realm_id", + "playable_state_namespace_id"); + private static final Set SHARED_NAMESPACE_FIELDS = + Set.of("tenant_id", "playable_state_namespace_id"); + private static final Set POINTER_EVENT_FIELDS = + Set.of( + "id", + "tenant_id", + "game_instance_id", + "world_slug", + "realm_slug", + "pointer_version", + "visible", + "requires_character_selection", + "state_scope", + "character_creation_policy", + "control_plane_request_id", + "prepared_version_upgrade_id", + "public_production_realm"); + private static final Set PREPARED_UPGRADE_FIELDS = + Set.of( + "id", + "tenant_id", + "preparation_id", + "control_plane_request_id", + "source_game_instance_id", + "source_version_id", + "target_version_id", + "target_launch_descriptor_id", + "remap_set_id", + "result", + "executed_target_game_instance_id", + "executed_pointer_version", + "execution_control_plane_request_id"); + private static final Set NULLABLE_INSTANCE_FIELDS = + Set.of( + "script_patch_version", + "game_template_id", + "launch_descriptor_id", + "version_id", + "release_bundle_id", + "version_state_epoch", + "generation_config_revision", + "remap_set_id", + "script_patch_pinned_control_plane_request_id", + "script_pin_epoch"); + private static final Set NULLABLE_POINTER_EVENT_FIELDS = + Set.of("prepared_version_upgrade_id"); + private static final Set NULLABLE_PREPARED_UPGRADE_FIELDS = + Set.of( + "remap_set_id", + "executed_target_game_instance_id", + "executed_pointer_version", + "execution_control_plane_request_id"); + + public GameSessionRetainedTenantSnapshot { + validateIdentity(targetNamespace, legacyGameSessionTenantId); + if (canonicalJson == null) { + throw new IllegalArgumentException("canonicalJson must not be null"); + } + if (evidenceDigest == null || !SHA256.matcher(evidenceDigest).matches()) { + throw new IllegalArgumentException("A canonical SHA-256 digest is required"); + } + validateCanonicalSnapshot(targetNamespace, legacyGameSessionTenantId, canonicalJson); + String expectedDigest = digest(canonicalJson); + if (!expectedDigest.equals(evidenceDigest)) { + throw new IllegalArgumentException("Retained-tenant snapshot digest does not match its JSON"); + } + } + + /** Revalidates stored canonical JSON and its digest without accepting caller-built maps. */ + public static GameSessionRetainedTenantSnapshot fromCanonicalJson( + String targetNamespace, + String legacyGameSessionTenantId, + String canonicalJson, + String evidenceDigest) { + return new GameSessionRetainedTenantSnapshot( + targetNamespace, legacyGameSessionTenantId, canonicalJson, evidenceDigest); + } + + static GameSessionRetainedTenantSnapshot fromProjection( + String targetNamespace, String legacyGameSessionTenantId, ObjectNode projection) { + validateIdentity(targetNamespace, legacyGameSessionTenantId); + if (projection == null) { + throw new IllegalArgumentException("projection must not be null"); + } + String canonicalJson = canonicalize(projection); + return new GameSessionRetainedTenantSnapshot( + targetNamespace, legacyGameSessionTenantId, canonicalJson, digest(canonicalJson)); + } + + static void validateIdentity(String targetNamespace, String legacyGameSessionTenantId) { + if (targetNamespace == null || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + BigInteger tenantId = parseDecimal(legacyGameSessionTenantId, "legacyGameSessionTenantId"); + if (tenantId.signum() <= 0 || tenantId.compareTo(LONG_MAX) > 0) { + throw new IllegalArgumentException("legacyGameSessionTenantId must be a positive BIGINT"); + } + } + + private static String canonicalize(ObjectNode projection) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)), + StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Retained-tenant snapshot is not canonical JSON", exception); + } + } + + private static void validateCanonicalSnapshot( + String targetNamespace, String legacyGameSessionTenantId, String canonicalJson) { + final JsonNode envelope; + final byte[] canonicalBytes; + try { + envelope = JSON.readTree(canonicalJson); + canonicalBytes = Rfc8785CanonicalJson.canonicalizeUtf8(canonicalJson); + } catch (IOException exception) { + throw new IllegalArgumentException("Retained-tenant snapshot JSON is malformed", exception); + } + if (envelope == null || !envelope.isObject()) { + throw new IllegalArgumentException("Retained-tenant snapshot must be a JSON object"); + } + if (!Arrays.equals(canonicalBytes, canonicalJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Retained-tenant snapshot JSON is not RFC 8785 canonical"); + } + ObjectNode object = (ObjectNode) envelope; + requireExactFields(object, ENVELOPE_FIELDS, "snapshot"); + JsonNode schemaVersion = object.get("schemaVersion"); + if (schemaVersion == null + || !schemaVersion.isIntegralNumber() + || !schemaVersion.canConvertToInt() + || schemaVersion.intValue() != 1) { + throw new IllegalArgumentException("snapshot.schemaVersion must be integer 1"); + } + requireExactText(object, "targetNamespace", targetNamespace, "snapshot"); + requireExactText(object, "legacyGameSessionTenantId", legacyGameSessionTenantId, "snapshot"); + + JsonNode instances = requireArray(object, "instances", "snapshot"); + JsonNode pointers = requireArray(object, "pointers", "snapshot"); + JsonNode sharedNamespaces = requireArray(object, "sharedNamespaces", "snapshot"); + JsonNode backfillIssues = requireArray(object, "backfillIssues", "snapshot"); + JsonNode pointerEvents = requireArray(object, "pointerEvents", "snapshot"); + JsonNode preparedUpgrades = requireArray(object, "preparedUpgrades", "snapshot"); + + if (!backfillIssues.isEmpty()) { + throw new IllegalArgumentException( + "snapshot.backfillIssues must be empty for valid evidence"); + } + + String tenantId = legacyGameSessionTenantId; + validateRows( + instances, + INSTANCE_FIELDS, + Set.of( + "id", + "tenant_id", + "owner_account_id", + "row_version", + "game_template_id", + "version_id", + "release_bundle_id", + "version_state_epoch", + "script_pin_epoch"), + Set.of("row_version"), + Set.of(), + Set.of(), + NULLABLE_INSTANCE_FIELDS, + "id", + tenantId, + "instances"); + validateRows( + pointers, + POINTER_FIELDS, + Set.of("id", "tenant_id", "game_instance_id", "pointer_version", "catalog_revision"), + Set.of(), + Set.of("realm_id", "playable_state_namespace_id"), + Set.of("visible", "requires_character_selection", "public_production_realm"), + Set.of(), + "id", + tenantId, + "pointers"); + validateRows( + sharedNamespaces, + SHARED_NAMESPACE_FIELDS, + Set.of("tenant_id"), + Set.of(), + Set.of("playable_state_namespace_id"), + Set.of(), + Set.of(), + "tenant_id", + tenantId, + "sharedNamespaces"); + validateRows( + pointerEvents, + POINTER_EVENT_FIELDS, + Set.of("id", "tenant_id", "game_instance_id", "pointer_version"), + Set.of(), + Set.of(), + Set.of("visible", "requires_character_selection", "public_production_realm"), + NULLABLE_POINTER_EVENT_FIELDS, + "id", + tenantId, + "pointerEvents"); + validateRows( + preparedUpgrades, + PREPARED_UPGRADE_FIELDS, + Set.of( + "id", + "tenant_id", + "source_game_instance_id", + "source_version_id", + "target_version_id", + "executed_target_game_instance_id", + "executed_pointer_version"), + Set.of(), + Set.of(), + Set.of(), + NULLABLE_PREPARED_UPGRADE_FIELDS, + "id", + tenantId, + "preparedUpgrades"); + + validatePointerRelationships(instances, pointers, sharedNamespaces, tenantId); + if (instances.isEmpty() + && pointers.isEmpty() + && sharedNamespaces.isEmpty() + && pointerEvents.isEmpty() + && preparedUpgrades.isEmpty()) { + throw new IllegalArgumentException("snapshot contains no retained tenant evidence"); + } + } + + private static void validateRows( + JsonNode rows, + Set fields, + Set numericFields, + Set nonnegativeNumericFields, + Set uuidFields, + Set booleanFields, + Set nullableFields, + String sortField, + String tenantId, + String path) { + BigInteger previousSortValue = null; + for (int index = 0; index < rows.size(); index++) { + JsonNode row = rows.get(index); + String rowPath = path + "[" + index + "]"; + if (row == null || !row.isObject()) { + throw new IllegalArgumentException(rowPath + " must be an object"); + } + ObjectNode object = (ObjectNode) row; + requireExactFields(object, fields, rowPath); + Iterator fieldNames = fields.iterator(); + while (fieldNames.hasNext()) { + String field = fieldNames.next(); + JsonNode value = object.get(field); + if (value == null) { + throw new IllegalArgumentException(rowPath + "." + field + " is required"); + } + if (value.isNull()) { + if (!nullableFields.contains(field)) { + throw new IllegalArgumentException(rowPath + "." + field + " may not be null"); + } + continue; + } + if (numericFields.contains(field)) { + BigInteger parsed = parseDecimalNode(value, rowPath + "." + field); + if (parsed.compareTo(LONG_MIN) < 0 || parsed.compareTo(LONG_MAX) > 0) { + throw new IllegalArgumentException( + rowPath + "." + field + " is outside SQL BIGINT bounds"); + } + if (parsed.signum() <= 0 && !nonnegativeNumericFields.contains(field)) { + throw new IllegalArgumentException(rowPath + "." + field + " must be positive"); + } + if (parsed.signum() < 0 && nonnegativeNumericFields.contains(field)) { + throw new IllegalArgumentException(rowPath + "." + field + " must be nonnegative"); + } + } else if (uuidFields.contains(field)) { + requireUuid(value, rowPath + "." + field); + } else if (booleanFields.contains(field)) { + if (!value.isBoolean()) { + throw new IllegalArgumentException(rowPath + "." + field + " must be a JSON boolean"); + } + } else if (!value.isTextual()) { + throw new IllegalArgumentException(rowPath + "." + field + " must be a JSON string"); + } + } + + JsonNode tenantNode = object.get("tenant_id"); + if (tenantNode != null && !tenantId.equals(tenantNode.textValue())) { + throw new IllegalArgumentException(rowPath + ".tenant_id contradicts the snapshot key"); + } + BigInteger sortValue = parseDecimalNode(object.get(sortField), rowPath + "." + sortField); + if (previousSortValue != null && sortValue.compareTo(previousSortValue) <= 0) { + throw new IllegalArgumentException(path + " must be strictly sorted by " + sortField); + } + previousSortValue = sortValue; + } + } + + private static void validatePointerRelationships( + JsonNode instances, JsonNode pointers, JsonNode sharedNamespaces, String tenantId) { + Set instanceIds = new java.util.HashSet<>(); + for (JsonNode instance : instances) { + instanceIds.add(instance.get("id").textValue()); + } + String sharedNamespaceId = + sharedNamespaces.isEmpty() + ? null + : sharedNamespaces.get(0).get("playable_state_namespace_id").textValue(); + if (sharedNamespaces.size() > 1) { + throw new IllegalArgumentException( + "sharedNamespaces may contain only the tenant's single allocation"); + } + Set realmIds = new java.util.HashSet<>(); + Set pointerInstanceIds = new java.util.HashSet<>(); + Set selectors = new java.util.HashSet<>(); + Set isolatedNamespaceIds = new java.util.HashSet<>(); + for (int index = 0; index < pointers.size(); index++) { + JsonNode pointer = pointers.get(index); + String path = "pointers[" + index + "]"; + if (!tenantId.equals(pointer.get("tenant_id").textValue())) { + throw new IllegalArgumentException(path + ".tenant_id contradicts the snapshot key"); + } + if (!instanceIds.contains(pointer.get("game_instance_id").textValue())) { + throw new IllegalArgumentException( + path + ".game_instance_id has no retained tenant instance"); + } + if (!realmIds.add(pointer.get("realm_id").textValue())) { + throw new IllegalArgumentException(path + ".realm_id contradicts another current pointer"); + } + if (!pointerInstanceIds.add(pointer.get("game_instance_id").textValue())) { + throw new IllegalArgumentException( + path + ".game_instance_id is bound by multiple current pointers"); + } + String selector = + pointer.get("world_slug").textValue() + "\u0000" + pointer.get("realm_slug").textValue(); + if (!selectors.add(selector)) { + throw new IllegalArgumentException(path + " duplicates another current pointer selector"); + } + String scope = pointer.get("state_scope").textValue(); + String pointerNamespace = pointer.get("playable_state_namespace_id").textValue(); + if ("SHARED".equals(scope)) { + if (sharedNamespaceId == null || !sharedNamespaceId.equals(pointerNamespace)) { + throw new IllegalArgumentException( + path + " does not match the tenant SHARED namespace allocation"); + } + } else if ("ISOLATED".equals(scope)) { + if (sharedNamespaceId != null && sharedNamespaceId.equals(pointerNamespace)) { + throw new IllegalArgumentException( + path + " uses the tenant SHARED allocation as ISOLATED state"); + } + if (!isolatedNamespaceIds.add(pointerNamespace)) { + throw new IllegalArgumentException( + path + " reuses another ISOLATED playable-state namespace"); + } + } else { + throw new IllegalArgumentException( + path + ".state_scope must be exactly SHARED or ISOLATED"); + } + } + } + + private static JsonNode requireArray(ObjectNode object, String field, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isArray()) { + throw new IllegalArgumentException(path + "." + field + " must be an array"); + } + return value; + } + + private static void requireExactFields(ObjectNode object, Set expected, String path) { + if (object.size() != expected.size()) { + throw new IllegalArgumentException(path + " has missing or undeclared fields"); + } + Iterator fields = object.fieldNames(); + while (fields.hasNext()) { + String field = fields.next(); + if (!expected.contains(field)) { + throw new IllegalArgumentException( + path + "." + field + " is not declared by schema version 1"); + } + } + for (String field : expected) { + if (!object.has(field)) { + throw new IllegalArgumentException(path + "." + field + " is required"); + } + } + } + + private static void requireExactText( + ObjectNode object, String field, String expected, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual() || !expected.equals(value.textValue())) { + throw new IllegalArgumentException( + path + "." + field + " does not match its snapshot selector"); + } + } + + private static BigInteger parseDecimalNode(JsonNode node, String path) { + if (node == null || !node.isTextual()) { + throw new IllegalArgumentException(path + " must be a canonical decimal string"); + } + return parseDecimal(node.textValue(), path); + } + + private static BigInteger parseDecimal(String value, String path) { + if (value == null || !CANONICAL_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(path + " must be a canonical decimal string"); + } + return new BigInteger(value); + } + + private static void requireUuid(JsonNode value, String path) { + if (!value.isTextual() || !CANONICAL_UUID.matcher(value.textValue()).matches()) { + throw new IllegalArgumentException(path + " must be a lowercase canonical UUID string"); + } + UUID parsed = UUID.fromString(value.textValue()); + if (parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(path + " must not be a nil UUID"); + } + } + + private static String digest(String canonicalJson) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + updateFrame(hash, DIGEST_DOMAIN); + updateFrame(hash, canonicalJson); + return "sha256:" + HexFormat.of().formatHex(hash.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void updateFrame(MessageDigest hash, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + hash.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + hash.update((byte) ':'); + hash.update(bytes); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepository.java new file mode 100644 index 0000000000..66c3f11a53 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepository.java @@ -0,0 +1,306 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Captures all retained Game Session tenant identity rows behind a short database write fence. */ +@Repository +public class GameSessionRetainedTenantSnapshotRepository { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String LOCK_SOURCE_FAMILIES = + "LOCK TABLE game_instances, gameplay_admission_pointer, " + + "gameplay_tenant_shared_playable_state_namespace, " + + "gameplay_admission_pointer_identity_backfill_issue, " + + "gameplay_admission_pointer_event, prepared_version_upgrade " + + "IN SHARE MODE NOWAIT"; + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Trusted Spring collaborator is validated before use; no resources or finalizer are acquired." + + " The repository remains non-final for transaction proxying.") + public GameSessionRetainedTenantSnapshotRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** + * Captures the retained owner projection under a caller-owned READ COMMITTED transaction. + * + *

The one-time SHARE fence conflicts with ordinary writes on each included relation and is + * retained until the caller's transaction commits or rolls back. Callers must not perform a + * network request while this owner transaction remains open. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GameSessionRetainedTenantSnapshot capture( + String targetNamespace, String legacyGameSessionTenantId) { + GameSessionRetainedTenantSnapshot.validateIdentity(targetNamespace, legacyGameSessionTenantId); + requireOwnerTransaction(); + + long tenantId = Long.parseLong(legacyGameSessionTenantId); + dsl.execute(LOCK_SOURCE_FAMILIES); + if (hasBackfillIssue(tenantId)) { + throw new InvalidRetainedTenantSnapshotException( + "Game Session retained tenant has an unresolved admission-pointer identity backfill issue"); + } + + ObjectNode envelope = JSON.createObjectNode(); + envelope.put("schemaVersion", 1); + envelope.put("targetNamespace", targetNamespace); + envelope.put("legacyGameSessionTenantId", legacyGameSessionTenantId); + envelope.set("instances", readInstances(tenantId)); + envelope.set("pointers", readPointers(tenantId)); + envelope.set("sharedNamespaces", readSharedNamespaces(tenantId)); + envelope.set("backfillIssues", JSON.createArrayNode()); + envelope.set("pointerEvents", readPointerEvents(tenantId)); + envelope.set("preparedUpgrades", readPreparedUpgrades(tenantId)); + return GameSessionRetainedTenantSnapshot.fromProjection( + targetNamespace, legacyGameSessionTenantId, envelope); + } + + private void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Retained-tenant snapshot requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Retained-tenant snapshot requires a read-write owner transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Retained-tenant snapshot requires the DSL connection to join the owner transaction"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Retained-tenant snapshot requires READ COMMITTED isolation"); + } + return null; + }); + Record isolationRow = dsl.fetchOne("SHOW transaction_isolation"); + String isolation = isolationRow == null ? null : isolationRow.get(0, String.class); + if (isolation == null || !"read committed".equalsIgnoreCase(isolation.trim())) { + throw new IllegalStateException("Retained-tenant snapshot requires READ COMMITTED isolation"); + } + Record readOnlyRow = dsl.fetchOne("SHOW transaction_read_only"); + String readOnly = readOnlyRow == null ? null : readOnlyRow.get(0, String.class); + if (readOnly == null || !"off".equalsIgnoreCase(readOnly.trim())) { + throw new IllegalStateException( + "Retained-tenant snapshot requires a read-write owner transaction"); + } + } + + private boolean hasBackfillIssue(long tenantId) { + return !dsl.fetch( + "SELECT 1 FROM gameplay_admission_pointer_identity_backfill_issue " + + "WHERE tenant_id = ? LIMIT 1", + tenantId) + .isEmpty(); + } + + private ArrayNode readInstances(long tenantId) { + return readRows( + "SELECT id, tenant_id, runtime_version, script_patch_version, owner_account_id, status, " + + "row_version, game_template_id, launch_descriptor_id, version_id, release_bundle_id, " + + "version_state_epoch, generation_config_revision, remap_set_id, " + + "script_patch_pinned_control_plane_request_id, script_pin_epoch " + + "FROM game_instances WHERE tenant_id = ? ORDER BY id ASC", + tenantId, + record -> { + ObjectNode row = JSON.createObjectNode(); + putLong(row, record, "id"); + putLong(row, record, "tenant_id"); + putText(row, record, "runtime_version"); + putNullableText(row, record, "script_patch_version"); + putLong(row, record, "owner_account_id"); + putText(row, record, "status"); + putLong(row, record, "row_version"); + putNullableLong(row, record, "game_template_id"); + putNullableText(row, record, "launch_descriptor_id"); + putNullableLong(row, record, "version_id"); + putNullableLong(row, record, "release_bundle_id"); + putNullableLong(row, record, "version_state_epoch"); + putNullableText(row, record, "generation_config_revision"); + putNullableText(row, record, "remap_set_id"); + putNullableText(row, record, "script_patch_pinned_control_plane_request_id"); + putNullableLong(row, record, "script_pin_epoch"); + return row; + }); + } + + private ArrayNode readPointers(long tenantId) { + return readRows( + "SELECT id, tenant_id, game_instance_id, world_slug, realm_slug, pointer_version, " + + "catalog_revision, visible, requires_character_selection, state_scope, " + + "character_creation_policy, public_production_realm, realm_id, " + + "playable_state_namespace_id FROM gameplay_admission_pointer " + + "WHERE tenant_id = ? ORDER BY id ASC", + tenantId, + record -> { + ObjectNode row = JSON.createObjectNode(); + putLong(row, record, "id"); + putLong(row, record, "tenant_id"); + putLong(row, record, "game_instance_id"); + putText(row, record, "world_slug"); + putText(row, record, "realm_slug"); + putLong(row, record, "pointer_version"); + putLong(row, record, "catalog_revision"); + putBoolean(row, record, "visible"); + putBoolean(row, record, "requires_character_selection"); + putText(row, record, "state_scope"); + putText(row, record, "character_creation_policy"); + putBoolean(row, record, "public_production_realm"); + putUuid(row, record, "realm_id"); + putUuid(row, record, "playable_state_namespace_id"); + return row; + }); + } + + private ArrayNode readSharedNamespaces(long tenantId) { + return readRows( + "SELECT tenant_id, playable_state_namespace_id " + + "FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ? ORDER BY tenant_id ASC", + tenantId, + record -> { + ObjectNode row = JSON.createObjectNode(); + putLong(row, record, "tenant_id"); + putUuid(row, record, "playable_state_namespace_id"); + return row; + }); + } + + private ArrayNode readPointerEvents(long tenantId) { + return readRows( + "SELECT id, tenant_id, game_instance_id, world_slug, realm_slug, pointer_version, visible, " + + "requires_character_selection, state_scope, character_creation_policy, " + + "control_plane_request_id, prepared_version_upgrade_id, public_production_realm " + + "FROM gameplay_admission_pointer_event WHERE tenant_id = ? ORDER BY id ASC", + tenantId, + record -> { + ObjectNode row = JSON.createObjectNode(); + putLong(row, record, "id"); + putLong(row, record, "tenant_id"); + putLong(row, record, "game_instance_id"); + putText(row, record, "world_slug"); + putText(row, record, "realm_slug"); + putLong(row, record, "pointer_version"); + putBoolean(row, record, "visible"); + putBoolean(row, record, "requires_character_selection"); + putText(row, record, "state_scope"); + putText(row, record, "character_creation_policy"); + putText(row, record, "control_plane_request_id"); + putNullableText(row, record, "prepared_version_upgrade_id"); + putBoolean(row, record, "public_production_realm"); + return row; + }); + } + + private ArrayNode readPreparedUpgrades(long tenantId) { + return readRows( + "SELECT id, tenant_id, preparation_id, control_plane_request_id, source_game_instance_id, " + + "source_version_id, target_version_id, target_launch_descriptor_id, remap_set_id, " + + "result, executed_target_game_instance_id, executed_pointer_version, " + + "execution_control_plane_request_id FROM prepared_version_upgrade " + + "WHERE tenant_id = ? ORDER BY id ASC", + tenantId, + record -> { + ObjectNode row = JSON.createObjectNode(); + putLong(row, record, "id"); + putLong(row, record, "tenant_id"); + putText(row, record, "preparation_id"); + putText(row, record, "control_plane_request_id"); + putLong(row, record, "source_game_instance_id"); + putLong(row, record, "source_version_id"); + putLong(row, record, "target_version_id"); + putText(row, record, "target_launch_descriptor_id"); + putNullableText(row, record, "remap_set_id"); + putText(row, record, "result"); + putNullableLong(row, record, "executed_target_game_instance_id"); + putNullableLong(row, record, "executed_pointer_version"); + putNullableText(row, record, "execution_control_plane_request_id"); + return row; + }); + } + + private ArrayNode readRows(String query, long tenantId, Function mapper) { + ArrayNode rows = JSON.createArrayNode(); + Result records = dsl.fetch(query, tenantId); + for (Record record : records) { + rows.add(mapper.apply(record)); + } + return rows; + } + + private static void putLong(ObjectNode node, Record record, String field) { + Long value = record.get(field, Long.class); + if (value == null) { + node.putNull(field); + } else { + node.put(field, Long.toString(value)); + } + } + + private static void putNullableLong(ObjectNode node, Record record, String field) { + Long value = record.get(field, Long.class); + if (value == null) { + node.putNull(field); + } else { + node.put(field, Long.toString(value)); + } + } + + private static void putText(ObjectNode node, Record record, String field) { + String value = record.get(field, String.class); + if (value == null) { + node.putNull(field); + } else { + node.put(field, value); + } + } + + private static void putNullableText(ObjectNode node, Record record, String field) { + putText(node, record, field); + } + + private static void putBoolean(ObjectNode node, Record record, String field) { + Boolean value = record.get(field, Boolean.class); + if (value == null) { + node.putNull(field); + } else { + node.put(field, value); + } + } + + private static void putUuid(ObjectNode node, Record record, String field) { + UUID value = record.get(field, UUID.class); + if (value == null) { + node.putNull(field); + } else { + node.put(field, value.toString()); + } + } + + /** Fail-closed owner evidence error for malformed or unresolved retained rows. */ + public static final class InvalidRetainedTenantSnapshotException extends IllegalStateException { + public InvalidRetainedTenantSnapshotException(String message) { + super(message); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationService.java new file mode 100644 index 0000000000..ded5ce90df --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationService.java @@ -0,0 +1,186 @@ +package net.firedevops.firemud.gamesession.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Base64; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient.LegacyGameSessionTenantAssociationReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.AssociationReceipt; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unwired source-to-owner transaction boundary for audited retained-tenant association. */ +@SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Trusted owner dependencies and namespace are validated before use; no resource or" + + " finalizer is acquired and this class is intentionally not a Spring bean.") +public class GameSessionRetainedTenantAssociationService { + private static final int SIGNATURE_BYTES = 64; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final GameDesignRuntimeTenantIdentityClient sourceClient; + private final GameSessionRetainedTenantAssociationRepository repository; + private final String workloadNamespace; + private final TransactionTemplate ownerTransaction; + + public GameSessionRetainedTenantAssociationService( + GameDesignRuntimeTenantIdentityClient sourceClient, + GameSessionRetainedTenantAssociationRepository repository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.sourceClient = Objects.requireNonNull(sourceClient, "sourceClient"); + this.repository = Objects.requireNonNull(repository, "repository"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * Resolves the authenticated Game Design owner receipt before opening a short local owner + * transaction, then commits its retained-row association. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED) + public AssociationReceipt associate( + String associationRequestId, + String canonicalTenantId, + String approvalOperationId, + String legacyGameSessionTenantId) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Retained-tenant association source read must begin outside an owner transaction"); + } + UUID requestUuid = parseCanonicalNonNilUuid(associationRequestId, "associationRequestId"); + UUID tenantUuid = parseCanonicalNonNilUuid(canonicalTenantId, "canonicalTenantId"); + UUID approvalOperationUuid = + parseCanonicalNonNilUuid(approvalOperationId, "approvalOperationId"); + String legacyKey = parseCanonicalPositiveBigint(legacyGameSessionTenantId); + + UUID readRequestUuid; + do { + readRequestUuid = UUID.randomUUID(); + } while (readRequestUuid.equals(requestUuid) || readRequestUuid.equals(approvalOperationUuid)); + + LegacyGameSessionTenantAssociationReceipt ownerReceipt = + sourceClient.resolveLegacyGameSessionTenantAssociation( + tenantUuid.toString(), + approvalOperationUuid.toString(), + legacyKey, + readRequestUuid.toString()); + LegacyGameSessionTenantAssociationReceipt validatedReceipt = + validateOwnerReceipt(ownerReceipt, tenantUuid, approvalOperationUuid, legacyKey); + + return ownerTransaction.execute(status -> repository.register(requestUuid, validatedReceipt)); + } + + private LegacyGameSessionTenantAssociationReceipt validateOwnerReceipt( + LegacyGameSessionTenantAssociationReceipt receipt, + UUID canonicalTenantId, + UUID approvalOperationId, + String legacyTenantKey) { + if (receipt == null || receipt.evidence() == null) { + throw new IllegalStateException("Authenticated Game Design approval receipt is missing"); + } + GameSessionTenantAssociationEvidence received = receipt.evidence(); + GameSessionTenantAssociationEvidence evidence; + try { + evidence = + new GameSessionTenantAssociationEvidence( + received.schemaVersion(), + received.operationId(), + received.targetNamespace(), + received.signerKeyId(), + received.approvedBy(), + received.approvalReference(), + received.signedAt(), + received.legacyGameSessionTenantId(), + received.canonicalTenantId(), + received.sourceGameRowId(), + received.sourceGameTenantKey(), + received.provenanceKind(), + received.gameSessionEvidenceDigest()); + } catch (RuntimeException exception) { + throw new IllegalStateException( + "Authenticated Game Design approval manifest is invalid", exception); + } + if (!workloadNamespace.equals(evidence.targetNamespace()) + || !approvalOperationId.equals(evidence.operationId()) + || !canonicalTenantId.equals(evidence.canonicalTenantId()) + || !legacyTenantKey.equals(evidence.legacyGameSessionTenantId())) { + throw new IllegalStateException( + "Authenticated Game Design approval receipt does not match the exact association"); + } + String manifestDigest = receipt.manifestDigest(); + if (manifestDigest == null || !evidence.manifestDigest().equals(manifestDigest)) { + throw new IllegalStateException( + "Authenticated Game Design approval digest does not match its manifest"); + } + requireCanonicalSignature(receipt.ed25519Signature()); + return new LegacyGameSessionTenantAssociationReceipt( + evidence, manifestDigest, receipt.ed25519Signature()); + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", exception); + } + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } + + private static String parseCanonicalPositiveBigint(String value) { + if (value == null || value.length() > 19 || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException( + "legacyGameSessionTenantId must be canonical positive BIGINT text"); + } + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException( + "legacyGameSessionTenantId must be canonical positive BIGINT text"); + } + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "legacyGameSessionTenantId must fit a positive PostgreSQL BIGINT", exception); + } + return value; + } + + private static void requireCanonicalSignature(String signature) { + if (signature == null) { + throw new IllegalStateException("Authenticated Game Design approval signature is missing"); + } + try { + byte[] bytes = Base64.getDecoder().decode(signature); + if (bytes.length != SIGNATURE_BYTES + || !Base64.getEncoder().encodeToString(bytes).equals(signature)) { + throw new IllegalStateException( + "Authenticated Game Design approval signature is not canonical Ed25519 base64"); + } + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Authenticated Game Design approval signature is invalid", exception); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V8__retained_tenant_association.sql b/services/game-session-service/src/main/resources/db/migration/V8__retained_tenant_association.sql new file mode 100644 index 0000000000..e024c89984 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V8__retained_tenant_association.sql @@ -0,0 +1,105 @@ +CREATE TABLE game_session_retained_tenant_association ( + operation_id UUID PRIMARY KEY, + approval_schema_version INTEGER NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + association_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + approval_operation_id UUID NOT NULL, + signer_key_id VARCHAR(128) NOT NULL, + approved_by VARCHAR(256) NOT NULL, + approval_reference VARCHAR(512) NOT NULL, + signed_at TEXT NOT NULL, + legacy_game_session_tenant_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + game_session_evidence_digest VARCHAR(71) NOT NULL, + approval_manifest_digest VARCHAR(71) NOT NULL, + approval_signature VARCHAR(88) NOT NULL, + snapshot_canonical_json TEXT NOT NULL, + snapshot_evidence_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_gs_retained_tenant_association_request + UNIQUE (target_namespace, association_request_id), + CONSTRAINT uq_gs_retained_tenant_association_canonical + UNIQUE (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gs_retained_tenant_association_legacy_key + UNIQUE (target_namespace, legacy_game_session_tenant_id), + CONSTRAINT chk_gs_retained_tenant_association_schema + CHECK (approval_schema_version = 1), + CONSTRAINT chk_gs_retained_tenant_association_operation_ids CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND association_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND approval_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gs_retained_tenant_association_namespace CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gs_retained_tenant_association_approval_labels CHECK ( + char_length(signer_key_id) BETWEEN 1 AND 128 + AND char_length(approved_by) BETWEEN 1 AND 256 + AND char_length(approval_reference) BETWEEN 1 AND 512 + AND octet_length(signer_key_id) <= 128 + AND octet_length(approved_by) <= 256 + AND octet_length(approval_reference) <= 512 + AND signer_key_id !~ '[[:cntrl:]]' + AND approved_by !~ '[[:cntrl:]]' + AND approval_reference !~ '[[:cntrl:]]' + AND signer_key_id !~ '^[[:space:]]*$' + AND approved_by !~ '^[[:space:]]*$' + AND approval_reference !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_retained_tenant_association_signed_at CHECK ( + char_length(signed_at) BETWEEN 1 AND 64 + ), + CONSTRAINT chk_gs_retained_tenant_association_retained_key CHECK ( + legacy_game_session_tenant_id > 0 + ), + CONSTRAINT chk_gs_retained_tenant_association_canonical_tenant CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gs_retained_tenant_association_source_row CHECK (source_game_row_id > 0), + CONSTRAINT chk_gs_retained_tenant_association_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_retained_tenant_association_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V30') + ), + CONSTRAINT chk_gs_retained_tenant_association_digests CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND game_session_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND approval_manifest_digest ~ '^sha256:[0-9a-f]{64}$' + AND snapshot_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gs_retained_tenant_association_signature CHECK ( + approval_signature ~ '^[A-Za-z0-9+/]{86}==$' + ), + CONSTRAINT chk_gs_retained_tenant_association_snapshot CHECK ( + octet_length(snapshot_canonical_json) > 0 + ) +); + +-- [jooq ignore start] +CREATE FUNCTION reject_game_session_retained_tenant_association_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session retained tenant association evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER game_session_retained_tenant_association_immutable +BEFORE UPDATE OR DELETE ON game_session_retained_tenant_association +FOR EACH ROW EXECUTE FUNCTION reject_game_session_retained_tenant_association_mutation(); + +CREATE TRIGGER game_session_retained_tenant_association_no_truncate +BEFORE TRUNCATE ON game_session_retained_tenant_association +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_retained_tenant_association_mutation(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java new file mode 100644 index 0000000000..244c1b387a --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationRepositoryIntegrationTest.java @@ -0,0 +1,606 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.SQLException; +import java.util.Base64; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient.LegacyGameSessionTenantAssociationReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.AssociationConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.AssociationReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.InvalidAssociationEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionRetainedTenantAssociationRepositoryIntegrationTest { + private static final String NAMESPACE = "retained-tenant-association-test"; + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final Table ASSOCIATIONS = + DSL.table(DSL.name("game_session_retained_tenant_association")); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void exactRetryReturnsHistoricalReceiptWithoutRecapturingChangedSource() { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-before-association"); + String sourceXminBefore = fixture.instanceXmin(420L); + GameSessionRetainedTenantSnapshot snapshot = fixture.capture(42L); + LegacyGameSessionTenantAssociationReceipt approval = + fixture.approval(uuid(101), uuid(201), 42L, snapshot); + + AssociationReceipt original = fixture.register(uuid(301), approval); + String associationXmin = fixture.associationXmin(uuid(301)); + String sourceXminAfter = fixture.instanceXmin(420L); + assertThat(sourceXminAfter).isEqualTo(sourceXminBefore); + + fixture.dsl.execute( + "UPDATE game_instances SET runtime_version = ? WHERE id = ?", + "runtime-after-association", + 420L); + assertThat(fixture.capture(42L).evidenceDigest()) + .isNotEqualTo(original.snapshot().evidenceDigest()); + + AssociationReceipt historicalRetry = fixture.register(uuid(301), approval); + assertThat(historicalRetry).isEqualTo(original); + assertThat(fixture.associationXmin(uuid(301))).isEqualTo(associationXmin); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + assertThat( + fixture.repository.read(original.operationId(), uuid(301), uuid(201), 42L, NAMESPACE)) + .contains(original); + assertThatThrownBy( + () -> fixture.repository.read(uuid(999), uuid(998), uuid(997), 42L, NAMESPACE)) + .isInstanceOf(InvalidAssociationEvidenceException.class) + .hasMessageContaining("contradictory local identity"); + assertThat(fixture.repository.read(uuid(999), uuid(998), uuid(997), 999L, NAMESPACE)).isEmpty(); + assertThatThrownBy( + () -> + fixture.repository.read( + original.operationId(), uuid(301), uuid(202), 42L, NAMESPACE)) + .isInstanceOf(InvalidAssociationEvidenceException.class); + assertThatThrownBy( + () -> + fixture.repository.read( + original.operationId(), uuid(302), uuid(201), 42L, NAMESPACE)) + .isInstanceOf(InvalidAssociationEvidenceException.class); + assertThatThrownBy( + () -> + fixture.repository.read( + original.operationId(), uuid(301), uuid(201), 43L, NAMESPACE)) + .isInstanceOf(InvalidAssociationEvidenceException.class); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> + fixture.repository.read( + original.operationId(), uuid(301), uuid(201), 42L, NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed-outcome owner read"); + } + + @Test + void committedReadRejectsForeignNamespaceBeforeDatabaseAccess() { + DSLContext dsl = mock(DSLContext.class); + GameSessionRetainedTenantSnapshotRepository snapshots = + mock(GameSessionRetainedTenantSnapshotRepository.class); + GameSessionRetainedTenantAssociationRepository repository = + new GameSessionRetainedTenantAssociationRepository(dsl, snapshots, NAMESPACE); + + assertThatThrownBy( + () -> repository.read(uuid(901), uuid(902), uuid(903), 42L, "other-namespace")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured Game Session workload namespace"); + + verifyNoInteractions(dsl, snapshots); + } + + @Test + void changedRequestAndOneToOneClaimConflictsLeaveNoPartialRows() { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-42"); + fixture.seedInstance(43L, 430L, "runtime-43"); + GameSessionRetainedTenantSnapshot snapshot42 = fixture.capture(42L); + GameSessionRetainedTenantSnapshot snapshot43 = fixture.capture(43L); + UUID firstRequest = uuid(401); + LegacyGameSessionTenantAssociationReceipt firstApproval = + fixture.approval(uuid(101), uuid(201), 42L, snapshot42); + AssociationReceipt first = fixture.register(firstRequest, firstApproval); + String originalXmin = fixture.associationXmin(firstRequest); + + LegacyGameSessionTenantAssociationReceipt changedApproval = + fixture.approval(uuid(102), uuid(202), 42L, snapshot42); + assertThatThrownBy(() -> fixture.register(firstRequest, changedApproval)) + .isInstanceOf(AssociationConflictException.class); + + assertThatThrownBy(() -> fixture.register(uuid(402), firstApproval)) + .isInstanceOf(AssociationConflictException.class); + + LegacyGameSessionTenantAssociationReceipt changedCanonicalClaim = + fixture.approval(uuid(103), uuid(201), 43L, snapshot43); + assertThatThrownBy(() -> fixture.register(uuid(403), changedCanonicalClaim)) + .isInstanceOf(AssociationConflictException.class); + + LegacyGameSessionTenantAssociationReceipt changedLegacyClaim = + fixture.approval(uuid(104), uuid(202), 42L, snapshot42); + assertThatThrownBy(() -> fixture.register(uuid(404), changedLegacyClaim)) + .isInstanceOf(AssociationConflictException.class); + + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + assertThat(fixture.associationXmin(firstRequest)).isEqualTo(originalXmin); + assertThat(fixture.storedRequestCount(firstRequest)).isEqualTo(1L); + assertThat(fixture.storedRequestCount(uuid(402))).isZero(); + assertThat(fixture.storedRequestCount(uuid(403))).isZero(); + assertThat(fixture.storedRequestCount(uuid(404))).isZero(); + assertThat( + fixture.repository.read(first.operationId(), firstRequest, uuid(201), 42L, NAMESPACE)) + .contains(first); + } + + @Test + void changedMissingAndExtraRetainedRowsRejectFirstCommit() { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-original"); + GameSessionRetainedTenantSnapshot originalSnapshot = fixture.capture(42L); + LegacyGameSessionTenantAssociationReceipt wrongDigestApproval = + fixture.approval(uuid(101), uuid(201), 42L, originalSnapshot, "sha256:" + "0".repeat(64)); + + assertThatThrownBy(() -> fixture.register(uuid(501), wrongDigestApproval)) + .isInstanceOf(InvalidAssociationEvidenceException.class) + .hasMessageContaining("does not match the approved owner evidence"); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isZero(); + + LegacyGameSessionTenantAssociationReceipt originalApproval = + fixture.approval(uuid(102), uuid(202), 42L, originalSnapshot); + fixture.dsl.execute( + "UPDATE game_instances SET runtime_version = ? WHERE id = ?", "runtime-changed", 420L); + assertThatThrownBy(() -> fixture.register(uuid(502), originalApproval)) + .isInstanceOf(InvalidAssociationEvidenceException.class) + .hasMessageContaining("does not match the approved owner evidence"); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isZero(); + + fixture.seedInstance(42L, 421L, "runtime-extra"); + assertThatThrownBy(() -> fixture.register(uuid(503), originalApproval)) + .isInstanceOf(InvalidAssociationEvidenceException.class) + .hasMessageContaining("does not match the approved owner evidence"); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isZero(); + + fixture.dsl.execute("DELETE FROM game_instances WHERE tenant_id = ?", 42L); + assertThatThrownBy(() -> fixture.register(uuid(504), originalApproval)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("no retained tenant evidence"); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isZero(); + } + + @Test + void lostAcknowledgementExactRetryReturnsSameOriginalOperationAndBytesWithoutMutation() { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-42"); + LegacyGameSessionTenantAssociationReceipt approval = + fixture.approval(uuid(101), uuid(201), 42L, fixture.capture(42L)); + UUID associationRequestId = uuid(601); + + // Model a committed response lost after the transaction: retain only the database baseline. + fixture.register(associationRequestId, approval); + Record committed = fixture.storedByRequest(associationRequestId); + UUID originalOperation = committed.get("operation_id", UUID.class); + String originalRequestDigest = committed.get("request_digest", String.class); + String originalManifestDigest = committed.get("approval_manifest_digest", String.class); + String originalSignature = committed.get("approval_signature", String.class); + assertThat(committed.get("target_namespace", String.class)).isEqualTo(NAMESPACE); + assertThat(originalManifestDigest).isEqualTo(approval.manifestDigest()); + assertThat(originalSignature).isEqualTo(approval.ed25519Signature()); + assertThat(originalRequestDigest) + .isEqualTo( + independentlyComputedRequestDigest( + NAMESPACE, + associationRequestId, + approval.manifestDigest(), + approval.ed25519Signature())); + String originalSnapshot = committed.get("snapshot_canonical_json", String.class); + String originalSnapshotDigest = committed.get("snapshot_evidence_digest", String.class); + String originalReceiptDigest = committed.get("receipt_digest", String.class); + byte[] originalSnapshotBytes = originalSnapshot.getBytes(StandardCharsets.UTF_8); + String originalXmin = fixture.associationXmin(associationRequestId); + + AssociationReceipt recovered = fixture.register(associationRequestId, approval); + + assertThat(recovered.operationId()).isEqualTo(originalOperation); + assertThat(recovered.requestDigest()).isEqualTo(originalRequestDigest); + assertThat(recovered.approvalManifestDigest()).isEqualTo(originalManifestDigest); + assertThat(recovered.approvalSignature()).isEqualTo(originalSignature); + assertThat(recovered.snapshot().canonicalJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(originalSnapshotBytes); + assertThat(recovered.snapshot().evidenceDigest()).isEqualTo(originalSnapshotDigest); + assertThat(recovered.receiptDigest()).isEqualTo(originalReceiptDigest); + assertThat(fixture.associationXmin(associationRequestId)).isEqualTo(originalXmin); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + @Test + void rollbackLeavesNoAssociationClaimAndNewAttemptSucceeds() { + Fixture fixture = fixture(); + fixture.seedInstance(43L, 430L, "runtime-43"); + UUID associationRequestId = uuid(602); + LegacyGameSessionTenantAssociationReceipt approval = + fixture.approval(uuid(103), uuid(203), 43L, fixture.capture(43L)); + + AssociationReceipt rolledBack = + fixture.transactions.execute( + status -> { + AssociationReceipt result = + fixture.repository.register(associationRequestId, approval); + status.setRollbackOnly(); + return result; + }); + assertThat(rolledBack).isNotNull(); + assertThat(fixture.storedRequestCount(associationRequestId)).isZero(); + assertThat( + fixture.repository.read( + rolledBack.operationId(), associationRequestId, uuid(203), 43L, NAMESPACE)) + .isEmpty(); + + AssociationReceipt retry = fixture.register(associationRequestId, approval); + assertThat(retry.operationId()).isNotEqualTo(rolledBack.operationId()); + assertThat( + fixture.repository.read( + retry.operationId(), associationRequestId, uuid(203), 43L, NAMESPACE)) + .contains(retry); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + @Test + void concurrentExactFirstWritersReturnSameImmutableReceipt() throws Exception { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-42"); + UUID associationRequestId = uuid(701); + LegacyGameSessionTenantAssociationReceipt approval = + fixture.approval(uuid(101), uuid(201), 42L, fixture.capture(42L)); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> { + ready.countDown(); + await(start, "concurrent registration start"); + return fixture.register(associationRequestId, approval); + }); + Future second = + executor.submit( + () -> { + ready.countDown(); + await(start, "concurrent registration start"); + return fixture.register(associationRequestId, approval); + }); + await(ready, "concurrent registration workers"); + start.countDown(); + + AssociationReceipt firstReceipt = first.get(15, TimeUnit.SECONDS); + AssociationReceipt secondReceipt = second.get(15, TimeUnit.SECONDS); + assertThat(secondReceipt).isEqualTo(firstReceipt); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + assertThat( + fixture.repository.read( + firstReceipt.operationId(), associationRequestId, uuid(201), 42L, NAMESPACE)) + .contains(firstReceipt); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void sourceWriterWaitsUntilAssociationCommitReleasesRetainedRowFence() throws Exception { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-fenced"); + UUID associationRequestId = uuid(702); + LegacyGameSessionTenantAssociationReceipt approval = + fixture.approval(uuid(101), uuid(201), 42L, fixture.capture(42L)); + CountDownLatch snapshotCaptured = new CountDownLatch(1); + CountDownLatch allowAssociationToContinue = new CountDownLatch(1); + CountDownLatch writerStarted = new CountDownLatch(1); + GameSessionRetainedTenantSnapshotRepository delayedSnapshots = spy(fixture.snapshotRepository); + doAnswer( + invocation -> { + var snapshot = invocation.callRealMethod(); + snapshotCaptured.countDown(); + await(allowAssociationToContinue, "association commit release"); + return snapshot; + }) + .when(delayedSnapshots) + .capture(eq(NAMESPACE), eq("42")); + GameSessionRetainedTenantAssociationRepository delayedRepository = + new GameSessionRetainedTenantAssociationRepository( + fixture.dsl, delayedSnapshots, NAMESPACE); + Fixture delayedFixture = + new Fixture(fixture.dsl, delayedSnapshots, delayedRepository, fixture.transactions); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future association = + executor.submit(() -> delayedFixture.register(associationRequestId, approval)); + await(snapshotCaptured, "fenced snapshot capture"); + Future sourceWriter = + executor.submit( + () -> { + writerStarted.countDown(); + fixture.dsl.execute( + "UPDATE game_instances SET runtime_version = ? WHERE id = ?", + "runtime-after-fence", + 420L); + }); + await(writerStarted, "source writer attempt"); + assertThatThrownBy(() -> sourceWriter.get(250, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + + allowAssociationToContinue.countDown(); + AssociationReceipt committed = association.get(10, TimeUnit.SECONDS); + sourceWriter.get(10, TimeUnit.SECONDS); + assertThat(committed.snapshot().evidenceDigest()) + .isNotEqualTo(fixture.capture(42L).evidenceDigest()); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + } finally { + allowAssociationToContinue.countDown(); + executor.shutdownNow(); + } + } + + @Test + void persistedRowsRejectUpdateDeleteAndTruncateThroughTheirOwnImmutableTriggers() { + Fixture fixture = fixture(); + fixture.seedInstance(42L, 420L, "runtime-42"); + UUID associationRequestId = uuid(801); + LegacyGameSessionTenantAssociationReceipt approval = + fixture.approval(uuid(101), uuid(201), 42L, fixture.capture(42L)); + fixture.register(associationRequestId, approval); + UUID operationId = + fixture.storedByRequest(associationRequestId).get("operation_id", UUID.class); + + assertCheckViolation( + () -> + fixture.dsl.execute( + "UPDATE game_session_retained_tenant_association SET approved_by = ? " + + "WHERE operation_id = ?", + "changed", + operationId)); + assertCheckViolation( + () -> + fixture.dsl.execute( + "DELETE FROM game_session_retained_tenant_association WHERE operation_id = ?", + operationId)); + assertCheckViolation( + () -> fixture.dsl.execute("TRUNCATE game_session_retained_tenant_association")); + assertThat(fixture.dsl.fetchCount(ASSOCIATIONS)).isEqualTo(1); + } + + private Fixture fixture() { + String schema = "gs_retained_tenant_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameSessionRetainedTenantSnapshotRepository snapshotRepository = + new GameSessionRetainedTenantSnapshotRepository(dsl); + GameSessionRetainedTenantAssociationRepository repository = + new GameSessionRetainedTenantAssociationRepository(dsl, snapshotRepository, NAMESPACE); + return new Fixture(dsl, snapshotRepository, repository, transactions); + } + + private static void assertCheckViolation( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { + Throwable failure = catchThrowable(action); + assertThat(failure).isInstanceOf(DataAccessException.class); + SQLException sqlException = findSqlException(failure); + assertThat((Throwable) sqlException).isNotNull(); + assertThat(sqlException.getSQLState()).isEqualTo("23514"); + } + + private static SQLException findSqlException(Throwable failure) { + Throwable current = failure; + while (current != null && !(current instanceof SQLException)) { + current = current.getCause(); + } + return (SQLException) current; + } + + private static void await(CountDownLatch latch, String label) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for " + label); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for " + label, exception); + } + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private static String independentlyComputedRequestDigest( + String exactNamespace, UUID associationRequestId, String manifestDigest, String signature) { + ByteArrayOutputStream framedPreimage = new ByteArrayOutputStream(); + for (String segment : + new String[] { + "game-session/retained-tenant-association-request/v1", + exactNamespace, + associationRequestId.toString(), + manifestDigest, + signature + }) { + byte[] segmentBytes = segment.getBytes(StandardCharsets.UTF_8); + framedPreimage.writeBytes( + Integer.toString(segmentBytes.length).getBytes(StandardCharsets.US_ASCII)); + framedPreimage.write(':'); + framedPreimage.writeBytes(segmentBytes); + } + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(framedPreimage.toByteArray())); + } catch (NoSuchAlgorithmException exception) { + throw new AssertionError("SHA-256 must be available", exception); + } + } + + private record Fixture( + DSLContext dsl, + GameSessionRetainedTenantSnapshotRepository snapshotRepository, + GameSessionRetainedTenantAssociationRepository repository, + TransactionTemplate transactions) { + void seedInstance(long tenantId, long instanceId, String runtimeVersion) { + dsl.execute( + "INSERT INTO game_instances " + + "(id, tenant_id, runtime_version, owner_account_id, status, row_version) " + + "VALUES (?, ?, ?, ?, ?, ?)", + instanceId, + tenantId, + runtimeVersion, + 9L, + "STOPPED", + 0L); + } + + GameSessionRetainedTenantSnapshot capture(long legacyTenantId) { + return Objects.requireNonNull( + transactions.execute( + status -> snapshotRepository.capture(NAMESPACE, Long.toString(legacyTenantId)))); + } + + LegacyGameSessionTenantAssociationReceipt approval( + UUID approvalOperationId, + UUID canonicalTenantId, + long legacyTenantId, + GameSessionRetainedTenantSnapshot snapshot) { + return approval( + approvalOperationId, + canonicalTenantId, + legacyTenantId, + snapshot, + snapshot.evidenceDigest()); + } + + LegacyGameSessionTenantAssociationReceipt approval( + UUID approvalOperationId, + UUID canonicalTenantId, + long legacyTenantId, + GameSessionRetainedTenantSnapshot snapshot, + String evidenceDigest) { + GameSessionTenantAssociationEvidence evidence = + new GameSessionTenantAssociationEvidence( + 1, + approvalOperationId, + NAMESPACE, + "fixture-owner-key", + "owner-reviewer", + "approval-" + approvalOperationId, + "2026-01-01T00:00:00Z", + Long.toString(legacyTenantId), + canonicalTenantId, + "501", + "source-game-501", + "RETAINED_GAME_V30", + evidenceDigest); + String signature = Base64.getEncoder().encodeToString(new byte[64]); + return new LegacyGameSessionTenantAssociationReceipt( + evidence, evidence.manifestDigest(), signature); + } + + AssociationReceipt register( + UUID associationRequestId, LegacyGameSessionTenantAssociationReceipt approval) { + return Objects.requireNonNull( + transactions.execute(status -> repository.register(associationRequestId, approval))); + } + + Record storedByRequest(UUID associationRequestId) { + return dsl.fetchOne( + "SELECT * FROM game_session_retained_tenant_association " + + "WHERE target_namespace = ? AND association_request_id = ?", + NAMESPACE, + associationRequestId); + } + + long storedRequestCount(UUID associationRequestId) { + Record row = + dsl.fetchOne( + "SELECT count(*) FROM game_session_retained_tenant_association " + + "WHERE target_namespace = ? AND association_request_id = ?", + NAMESPACE, + associationRequestId); + return Objects.requireNonNull( + Objects.requireNonNull(row, "COUNT query must return a row").get(0, Long.class), + "COUNT query returned null"); + } + + String associationXmin(UUID associationRequestId) { + Record row = + dsl.fetchOne( + "SELECT xmin::text AS xmin FROM game_session_retained_tenant_association " + + "WHERE target_namespace = ? AND association_request_id = ?", + NAMESPACE, + associationRequestId); + return Objects.requireNonNull(row).get("xmin", String.class); + } + + String instanceXmin(long instanceId) { + Record row = + dsl.fetchOne("SELECT xmin::text AS xmin FROM game_instances WHERE id = ?", instanceId); + return Objects.requireNonNull(row).get("xmin", String.class); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java new file mode 100644 index 0000000000..5194ae5af6 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotRepositoryIntegrationTest.java @@ -0,0 +1,513 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshotRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionRetainedTenantSnapshotRepositoryIntegrationTest { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String NAMESPACE = "retained-snapshot-test"; + private static final String TENANT_ID = "70123"; + private static final long TENANT = Long.parseLong(TENANT_ID); + private static final long OTHER_TENANT = TENANT + 1; + private static final UUID SHARED_NAMESPACE = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID ISOLATED_NAMESPACE = + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID REALM_SHARED = UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID REALM_ISOLATED = + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final String COMMITTED_INSTANCE_PHANTOM_INSERT = + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, status, row_version) " + + "VALUES (901, " + + TENANT + + ", 'phantom', 90123, 'STOPPED', 0)"; + private static final String COMMITTED_POINTER_PHANTOM_INSERT = + "INSERT INTO gameplay_admission_pointer (id, world_slug, world_display_name, realm_slug, " + + "realm_display_name, tenant_id, game_instance_id, pointer_version, visible, " + + "requires_character_selection, state_scope, character_creation_policy, last_updated_by, " + + "last_update_reason, public_production_realm, realm_id, playable_state_namespace_id) " + + "VALUES (902, 'phantom-world', 'Phantom', 'phantom-realm', 'Phantom realm', " + + TENANT + + ", 901, 1, false, false, 'ISOLATED', 'DISABLED', 'test', 'fence test', false, " + + "'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', 'ffffffff-ffff-4fff-8fff-ffffffffffff')"; + // The integration runtime includes other services' migration resources; scan this module only. + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void capturesExactOrderedTenantProjectionAndStableDigestUnderReadCommittedOwnerTransaction() + throws Exception { + Fixture fixture = fixture(); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> fixture.repository.capture(NAMESPACE, Long.toString(OTHER_TENANT)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("no retained tenant evidence"); + fixture.seedProjection(); + + assertThatThrownBy(() -> fixture.repository.capture(NAMESPACE, TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + + GameSessionRetainedTenantSnapshot snapshot = fixture.capture(); + JsonNode root = JSON.readTree(snapshot.canonicalJson()); + assertThat(root.get("schemaVersion").intValue()).isEqualTo(1); + assertThat(root.get("targetNamespace").textValue()).isEqualTo(NAMESPACE); + assertThat(root.get("legacyGameSessionTenantId").textValue()).isEqualTo(TENANT_ID); + assertThat(textValues(root.get("instances"), "id")).containsExactly("2", "10", "20"); + assertThat(root.get("instances").get(1).get("runtime_version").textValue()) + .isEqualTo("Café 🐉"); + assertThat(root.get("instances").get(1).get("row_version").textValue()) + .isEqualTo("9223372036854775807"); + assertThat(textValues(root.get("pointers"), "id")).containsExactly("2", "10"); + assertThat(root.get("pointers").get(1).get("catalog_revision").textValue()) + .isEqualTo("9223372036854775807"); + assertThat(root.get("pointerEvents").get(1).get("game_instance_id").textValue()) + .isEqualTo("888888"); + assertThat( + root.get("preparedUpgrades").get(0).get("executed_target_game_instance_id").textValue()) + .isEqualTo("999999"); + assertThat(root.get("backfillIssues").size()).isZero(); + assertThat( + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, snapshot.canonicalJson(), snapshot.evidenceDigest())) + .isEqualTo(snapshot); + + TransactionTemplate readOnly = new TransactionTemplate(fixture.transactionManager); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> readOnly.execute(status -> fixture.repository.capture(NAMESPACE, TENANT_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("read-write owner transaction"); + + TransactionTemplate repeatableRead = new TransactionTemplate(fixture.transactionManager); + repeatableRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThatThrownBy( + () -> + repeatableRead.execute(status -> fixture.repository.capture(NAMESPACE, TENANT_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ COMMITTED"); + + GameSessionRetainedTenantSnapshotRepository autocommitRepository = + new GameSessionRetainedTenantSnapshotRepository(fixture.autocommitDsl); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> autocommitRepository.capture(NAMESPACE, TENANT_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("DSL connection to join the owner transaction"); + + fixture.dsl.execute( + "INSERT INTO gameplay_admission_pointer_identity_backfill_issue " + + "(pointer_id, tenant_id, world_slug, realm_slug, prior_state_scope, issue_code) " + + "VALUES (?, ?, ?, ?, ?, ?)", + 400L, + TENANT, + "affected-world", + "affected-realm", + "UNKNOWN", + "TEST_UNRESOLVED"); + assertThatThrownBy(fixture::capture) + .isInstanceOf( + GameSessionRetainedTenantSnapshotRepository.InvalidRetainedTenantSnapshotException + .class) + .hasMessageContaining("backfill issue"); + } + + @Test + void captureUsesNowaitToRejectAnExistingWriterThenSucceedsAfterRollback() throws Exception { + Fixture fixture = fixture(); + fixture.seedProjection(); + CountDownLatch writerReady = new CountDownLatch(1); + CountDownLatch finishWriter = new CountDownLatch(1); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future writer = + executor.submit( + () -> + fixture.transactions.execute( + status -> { + fixture.dsl.execute( + "UPDATE game_instances SET runtime_version = ? WHERE id = ?", + "uncommitted-writer", + 10L); + writerReady.countDown(); + await(finishWriter); + status.setRollbackOnly(); + return null; + })); + assertThat(writerReady.await(10, TimeUnit.SECONDS)).isTrue(); + assertThatThrownBy(fixture::capture).isInstanceOf(DataAccessException.class); + finishWriter.countDown(); + writer.get(10, TimeUnit.SECONDS); + assertThat(fixture.capture().canonicalJson()).contains("Café 🐉"); + } finally { + finishWriter.countDown(); + executor.shutdownNow(); + } + } + + @Test + void + shareFenceBlocksConcurrentInsertUpdateDeleteAcrossEverySourceFamilyAndReleasesAfterCommitOrRollback() + throws Exception { + Fixture fixture = fixture(); + fixture.seedProjection(); + GameSessionRetainedTenantSnapshot originalSnapshot = fixture.capture(); + + fixture.transactions.execute( + status -> { + fixture.repository.capture(NAMESPACE, TENANT_ID); + for (MutationCase mutation : mutationCases()) { + fixture.assertMutationBlocked(mutation.insertSql()); + fixture.assertMutationBlocked(mutation.updateSql()); + fixture.assertMutationBlocked(mutation.deleteSql()); + } + return null; + }); + + fixture.assertMutationMatrixSucceedsThenRollsBack(); + assertThat(fixture.capture().evidenceDigest()).isEqualTo(originalSnapshot.evidenceDigest()); + fixture.executeMutation(COMMITTED_INSTANCE_PHANTOM_INSERT); + Long instancePhantomCount = + java.util.Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT count(*) FROM game_instances WHERE id = 901 AND tenant_id = ?", TENANT)) + .get(0, Long.class); + assertThat(instancePhantomCount).isEqualTo(1L); + GameSessionRetainedTenantSnapshot afterInstanceInsert = fixture.capture(); + assertThat(afterInstanceInsert.evidenceDigest()) + .isNotEqualTo(originalSnapshot.evidenceDigest()); + + fixture.transactions.execute( + status -> { + fixture.repository.capture(NAMESPACE, TENANT_ID); + status.setRollbackOnly(); + return null; + }); + fixture.assertMutationMatrixSucceedsThenRollsBack(); + assertThat(fixture.capture().evidenceDigest()).isEqualTo(afterInstanceInsert.evidenceDigest()); + fixture.executeMutation(COMMITTED_POINTER_PHANTOM_INSERT); + Long pointerPhantomCount = + java.util.Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT count(*) FROM gameplay_admission_pointer WHERE id = 902 AND tenant_id = ? " + + "AND game_instance_id = 901", + TENANT)) + .get(0, Long.class); + assertThat(pointerPhantomCount).isEqualTo(1L); + GameSessionRetainedTenantSnapshot afterPointerInsert = fixture.capture(); + assertThat(afterPointerInsert.evidenceDigest()) + .isNotEqualTo(afterInstanceInsert.evidenceDigest()); + } + + private Fixture fixture() { + String schema = "gs_retained_snapshot_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DSLContext autocommitDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + return new Fixture( + dataSource, + transactionManager, + transactions, + dsl, + autocommitDsl, + new GameSessionRetainedTenantSnapshotRepository(dsl)); + } + + private static List textValues(JsonNode rows, String field) { + java.util.ArrayList values = new java.util.ArrayList<>(); + for (JsonNode row : rows) { + values.add(row.get(field).textValue()); + } + return values; + } + + private static List mutationCases() { + return List.of( + new MutationCase( + "game_instances", + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, status, row_version) " + + "VALUES (911, " + + TENANT + + ", 'matrix-phantom', 90123, 'STOPPED', 0)", + "UPDATE game_instances SET runtime_version = 'matrix-updated' WHERE id = 10 AND tenant_id = " + + TENANT, + "DELETE FROM game_instances WHERE id = 10 AND tenant_id = " + TENANT), + new MutationCase( + "gameplay_admission_pointer", + "INSERT INTO gameplay_admission_pointer (id, world_slug, world_display_name, realm_slug, " + + "realm_display_name, tenant_id, game_instance_id, pointer_version, visible, " + + "requires_character_selection, state_scope, character_creation_policy, " + + "last_updated_by, last_update_reason, public_production_realm, realm_id, " + + "playable_state_namespace_id) VALUES (912, 'matrix-world', 'Matrix', " + + "'matrix-realm', 'Matrix realm', " + + TENANT + + ", 20, 1, false, false, " + + "'ISOLATED', 'DISABLED', 'test', 'fence test', false, " + + "'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', " + + "'ffffffff-ffff-4fff-8fff-ffffffffffff')", + "UPDATE gameplay_admission_pointer SET last_update_reason = 'matrix-updated' " + + "WHERE id = 10 AND tenant_id = " + + TENANT, + "DELETE FROM gameplay_admission_pointer WHERE id = 10 AND tenant_id = " + TENANT), + new MutationCase( + "gameplay_tenant_shared_playable_state_namespace", + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (" + + OTHER_TENANT + + ", '11111111-2222-4333-8444-555555555555')", + "UPDATE gameplay_tenant_shared_playable_state_namespace SET " + + "playable_state_namespace_id = '22222222-3333-4444-8555-666666666666' " + + "WHERE tenant_id = " + + TENANT, + "DELETE FROM gameplay_tenant_shared_playable_state_namespace WHERE tenant_id = " + + TENANT), + new MutationCase( + "gameplay_admission_pointer_identity_backfill_issue", + "INSERT INTO gameplay_admission_pointer_identity_backfill_issue " + + "(pointer_id, tenant_id, world_slug, realm_slug, prior_state_scope, issue_code) " + + "VALUES (903, " + + OTHER_TENANT + + ", 'phantom-world', 'phantom-realm', 'UNKNOWN', 'TEST')", + "UPDATE gameplay_admission_pointer_identity_backfill_issue SET issue_code = 'MATRIX_UPDATED' " + + "WHERE pointer_id = 399 AND tenant_id = " + + OTHER_TENANT, + "DELETE FROM gameplay_admission_pointer_identity_backfill_issue WHERE pointer_id = 399 " + + "AND tenant_id = " + + OTHER_TENANT), + new MutationCase( + "gameplay_admission_pointer_event", + "INSERT INTO gameplay_admission_pointer_event (id, world_slug, realm_slug, " + + "world_display_name, realm_display_name, tenant_id, game_instance_id, pointer_version, " + + "visible, requires_character_selection, state_scope, character_creation_policy, " + + "actor_principal, reason, control_plane_request_id, public_production_realm) " + + "VALUES (904, 'phantom-world', 'phantom-realm', 'Phantom', 'Phantom realm', " + + OTHER_TENANT + + ", 21, 1, false, false, 'ISOLATED', 'DISABLED', 'test', " + + "'fence test', 'request-phantom-event', false)", + "UPDATE gameplay_admission_pointer_event SET reason = 'matrix-updated' " + + "WHERE id = 10 AND tenant_id = " + + TENANT, + "DELETE FROM gameplay_admission_pointer_event WHERE id = 10 AND tenant_id = " + TENANT), + new MutationCase( + "prepared_version_upgrade", + "INSERT INTO prepared_version_upgrade (id, preparation_id, control_plane_request_id, " + + "tenant_id, source_game_instance_id, source_version_id, target_version_id, " + + "target_launch_descriptor_id, result, reasons_json, checked_participants_json, " + + "participant_results_json, checked_at) VALUES (905, 'phantom-preparation', " + + "'phantom-request', " + + OTHER_TENANT + + ", 21, 1, 2, 'phantom-launch', 'CHECKED', " + + "'[]', '[]', '[]', CURRENT_TIMESTAMP)", + "UPDATE prepared_version_upgrade SET result = 'MATRIX_UPDATED' WHERE id = 3 AND tenant_id = " + + TENANT, + "DELETE FROM prepared_version_upgrade WHERE id = 3 AND tenant_id = " + TENANT)); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for retained-tenant writer"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for retained-tenant writer", exception); + } + } + + private record MutationCase(String table, String insertSql, String updateSql, String deleteSql) {} + + private record Fixture( + DriverManagerDataSource dataSource, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions, + DSLContext dsl, + DSLContext autocommitDsl, + GameSessionRetainedTenantSnapshotRepository repository) { + GameSessionRetainedTenantSnapshot capture() { + GameSessionRetainedTenantSnapshot snapshot = + transactions.execute(status -> repository.capture(NAMESPACE, TENANT_ID)); + return java.util.Objects.requireNonNull(snapshot); + } + + void seedProjection() { + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, status, row_version) " + + "VALUES (10, ?, 'Café 🐉', 90010, 'STOPPED', ?), " + + "(2, ?, 'runtime-two', 90002, 'STOPPED', 0)", + TENANT, + Long.MAX_VALUE, + TENANT); + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, status, row_version) " + + "VALUES (20, ?, 'matrix-pointer-target', 90020, 'STOPPED', 0), " + + "(21, ?, 'other-tenant-history-target', 90021, 'STOPPED', 0)", + TENANT, + OTHER_TENANT); + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?)", + TENANT, + SHARED_NAMESPACE); + dsl.execute( + "INSERT INTO gameplay_admission_pointer (id, world_slug, world_display_name, realm_slug, " + + "realm_display_name, tenant_id, game_instance_id, pointer_version, visible, " + + "requires_character_selection, state_scope, character_creation_policy, last_updated_by, " + + "last_update_reason, public_production_realm, realm_id, playable_state_namespace_id, " + + "catalog_revision) VALUES (10, 'north-star', 'Café World', 'quiet-bay', 'Quiet Bay', " + + "?, 10, ?, true, true, 'ISOLATED', 'DISABLED', 'seed', 'projection fixture', false, " + + "?, ?, ?), (2, 'north-star', 'Café World', 'shared-square', 'Shared Square', ?, 2, 1, " + + "true, false, 'SHARED', 'DISABLED', 'seed', 'projection fixture', true, ?, ?, 1)", + TENANT, + Long.MAX_VALUE, + REALM_ISOLATED, + ISOLATED_NAMESPACE, + Long.MAX_VALUE, + TENANT, + REALM_SHARED, + SHARED_NAMESPACE); + dsl.execute( + "INSERT INTO gameplay_admission_pointer_event (id, world_slug, realm_slug, world_display_name, " + + "realm_display_name, tenant_id, game_instance_id, pointer_version, visible, " + + "requires_character_selection, state_scope, character_creation_policy, actor_principal, " + + "reason, control_plane_request_id, prepared_version_upgrade_id, public_production_realm) " + + "VALUES (10, 'old-world', 'old-realm', 'Old world', 'Old realm', ?, 888888, ?, false, " + + "false, 'ISOLATED', 'DISABLED', 'historical-operator', 'retained history', 'event-ten', " + + "'missing-upgrade', false), (2, 'old-world', 'old-realm-two', 'Old world', 'Old realm', " + + "?, 777777, 1, true, false, 'SHARED', 'DISABLED', 'historical-operator', " + + "'retained history', 'event-two', null, true)", + TENANT, + Long.MAX_VALUE, + TENANT); + dsl.execute( + "INSERT INTO prepared_version_upgrade (id, preparation_id, control_plane_request_id, tenant_id, " + + "source_game_instance_id, source_version_id, target_version_id, target_launch_descriptor_id, " + + "remap_set_id, result, reasons_json, checked_participants_json, participant_results_json, " + + "checked_at, executed_target_game_instance_id, executed_pointer_version, " + + "execution_control_plane_request_id) VALUES (3, 'preparation-three', 'upgrade-request-three', " + + "?, 888888, 99, 100, 'launch-descriptor', null, 'CHECKED', '[]', '[]', '[]', " + + "CURRENT_TIMESTAMP, 999999, ?, 'execution-request-three')", + TENANT, + Long.MAX_VALUE); + dsl.execute( + "INSERT INTO gameplay_admission_pointer_identity_backfill_issue " + + "(pointer_id, tenant_id, world_slug, realm_slug, prior_state_scope, issue_code) " + + "VALUES (399, ?, 'other-tenant-world', 'other-tenant-realm', 'UNKNOWN', 'TEST_FIXTURE')", + OTHER_TENANT); + } + + void assertMutationBlocked(String sql) { + try (Connection connection = dataSource.getConnection()) { + connection.setAutoCommit(false); + try (Statement statement = connection.createStatement()) { + statement.execute("SET LOCAL lock_timeout = '200ms'"); + statement.execute(sql); + connection.commit(); + throw new AssertionError( + "Mutation unexpectedly passed the retained-tenant fence: " + sql); + } catch (SQLException exception) { + connection.rollback(); + assertThat(exception.getSQLState()) + .as("mutation should time out on its relation lock: %s", sql) + .isEqualTo("55P03"); + } + } catch (SQLException exception) { + throw new IllegalStateException("Unable to test retained-tenant relation fence", exception); + } + } + + void assertMutationMatrixSucceedsThenRollsBack() { + for (MutationCase mutation : mutationCases()) { + assertMutationSucceedsThenRollsBack(mutation.insertSql()); + assertMutationSucceedsThenRollsBack(mutation.updateSql()); + assertMutationSucceedsThenRollsBack(mutation.deleteSql()); + } + } + + private void assertMutationSucceedsThenRollsBack(String sql) { + try (Connection connection = dataSource.getConnection()) { + connection.setAutoCommit(false); + try { + try (Statement statement = connection.createStatement()) { + statement.execute("SET LOCAL lock_timeout = '200ms'"); + int affectedRows = statement.executeUpdate(sql); + assertThat(affectedRows) + .as("mutation must change an existing or newly inserted row: %s", sql) + .isPositive(); + } + } finally { + connection.rollback(); + } + } catch (SQLException exception) { + throw new IllegalStateException( + "Mutation did not affect a row after retained-tenant transaction", exception); + } + } + + void executeMutation(String sql) { + try (Connection connection = dataSource.getConnection(); + Statement statement = connection.createStatement()) { + connection.setAutoCommit(false); + statement.execute("SET LOCAL lock_timeout = '200ms'"); + statement.execute(sql); + connection.commit(); + } catch (SQLException exception) { + throw new IllegalStateException( + "Mutation remained blocked after retained-tenant transaction", exception); + } + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotTest.java new file mode 100644 index 0000000000..5dca3d5108 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshotTest.java @@ -0,0 +1,213 @@ +package unit.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantSnapshot; +import org.junit.jupiter.api.Test; + +class GameSessionRetainedTenantSnapshotTest { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String NAMESPACE = "retained-snapshot-test"; + private static final String TENANT_ID = "7"; + private static final String SNAPSHOT_DIGEST = + "sha256:66c92bb8e82371c03d24d9cfaa14c7e7c033b8a4a53d081bc05214cf501e22a1"; + private static final String CHANGED_SNAPSHOT_DIGEST = + "sha256:5652fc676448cc7dc8e45453f2577915d6ded0a0f1b00bbf1ee84b59673b27e6"; + private static final String IRRELEVANT_DIGEST = "sha256:" + "0".repeat(64); + + @Test + void emitsCanonicalOrderedUnicodeAndLargeCounterVectorAndBindsChangedFields() { + String canonicalJson = snapshotJson("Café 🐉"); + GameSessionRetainedTenantSnapshot snapshot = + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, canonicalJson, SNAPSHOT_DIGEST); + + assertThat(snapshot.canonicalJson()) + .startsWith("{\"backfillIssues\":[],\"instances\":[") + .contains("\"runtime_version\":\"Café 🐉\"") + .contains("\"row_version\":\"9223372036854775807\""); + assertThat(snapshot.canonicalJson().indexOf("\"id\":\"2\"")) + .isLessThan(snapshot.canonicalJson().indexOf("\"id\":\"10\"")); + assertThat(snapshot.evidenceDigest()).isEqualTo(SNAPSHOT_DIGEST); + assertThat( + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, snapshot.canonicalJson(), snapshot.evidenceDigest())) + .isEqualTo(snapshot); + + GameSessionRetainedTenantSnapshot changed = + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, snapshotJson("Café 🐲"), CHANGED_SNAPSHOT_DIGEST); + assertThat(changed.evidenceDigest()).isNotEqualTo(snapshot.evidenceDigest()); + assertThatThrownBy( + () -> + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, snapshot.canonicalJson(), IRRELEVANT_DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest"); + } + + @Test + void rejectsEmptyUnknownMalformedAndDuplicateMemberEvidence() { + ObjectNode empty = envelope(); + assertThatThrownBy(() -> revalidate(empty)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("no retained tenant evidence"); + + ObjectNode unknown = envelopeWithInstances("Café 🐉"); + unknown.put("unexpected", "evidence"); + assertThatThrownBy(() -> revalidate(unknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("undeclared"); + + ObjectNode malformedNumeric = envelopeWithInstances("Café 🐉"); + ((ObjectNode) malformedNumeric.withArray("instances").get(0)).put("id", "01"); + assertThatThrownBy(() -> revalidate(malformedNumeric)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical decimal"); + + ObjectNode malformedUuid = envelopeWithInstances("Café 🐉"); + ObjectNode pointer = pointer("2", "not-a-uuid"); + malformedUuid.withArray("pointers").add(pointer); + assertThatThrownBy(() -> revalidate(malformedUuid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lowercase canonical UUID"); + + ObjectNode missingInstance = envelopeWithInstances("Café 🐉"); + missingInstance + .withArray("pointers") + .add(pointer("999", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee")); + assertThatThrownBy(() -> revalidate(missingInstance)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("no retained tenant instance"); + + ObjectNode unresolvedBackfill = envelopeWithInstances("Café 🐉"); + unresolvedBackfill.withArray("backfillIssues").add(JSON.createObjectNode()); + assertThatThrownBy(() -> revalidate(unresolvedBackfill)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("backfillIssues must be empty"); + + String valid = snapshotJson("Café 🐉"); + String duplicateMemberJson = + valid.replace( + "\"targetNamespace\":\"" + NAMESPACE + "\"", + "\"targetNamespace\":\"" + NAMESPACE + "\",\"targetNamespace\":\"" + NAMESPACE + "\""); + assertThatThrownBy( + () -> + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, duplicateMemberJson, SNAPSHOT_DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("malformed"); + } + + @Test + void rejectsNonCanonicalNamespaceAndLegacyTenantKeys() { + String valid = snapshotJson("runtime"); + assertThatThrownBy( + () -> + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + "Invalid-Namespace", TENANT_ID, valid, IRRELEVANT_DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); + assertThatThrownBy( + () -> + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, "07", valid, IRRELEVANT_DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical decimal"); + assertThatThrownBy( + () -> + GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, "9223372036854775808", valid, IRRELEVANT_DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive BIGINT"); + } + + private static GameSessionRetainedTenantSnapshot revalidate(ObjectNode projection) { + return GameSessionRetainedTenantSnapshot.fromCanonicalJson( + NAMESPACE, TENANT_ID, canonicalJson(projection), IRRELEVANT_DIGEST); + } + + private static String snapshotJson(String runtimeVersion) { + return canonicalJson(envelopeWithInstances(runtimeVersion)); + } + + private static ObjectNode envelopeWithInstances(String runtimeVersion) { + ObjectNode envelope = envelope(); + ArrayNode instances = JSON.createArrayNode(); + instances.add(instance("2", "old-runtime", "0")); + instances.add(instance("10", runtimeVersion, "9223372036854775807")); + envelope.set("instances", instances); + return envelope; + } + + private static ObjectNode envelope() { + ObjectNode envelope = JSON.createObjectNode(); + envelope.put("targetNamespace", NAMESPACE); + envelope.put("schemaVersion", 1); + envelope.put("legacyGameSessionTenantId", TENANT_ID); + envelope.set("instances", JSON.createArrayNode()); + envelope.set("pointers", JSON.createArrayNode()); + envelope.set("sharedNamespaces", JSON.createArrayNode()); + envelope.set("backfillIssues", JSON.createArrayNode()); + envelope.set("pointerEvents", JSON.createArrayNode()); + envelope.set("preparedUpgrades", JSON.createArrayNode()); + return envelope; + } + + private static ObjectNode instance(String id, String runtimeVersion, String rowVersion) { + ObjectNode instance = JSON.createObjectNode(); + instance.put("id", id); + instance.put("tenant_id", TENANT_ID); + instance.put("runtime_version", runtimeVersion); + instance.putNull("script_patch_version"); + instance.put("owner_account_id", "9"); + instance.put("status", "STOPPED"); + instance.put("row_version", rowVersion); + instance.putNull("game_template_id"); + instance.putNull("launch_descriptor_id"); + instance.putNull("version_id"); + instance.putNull("release_bundle_id"); + instance.putNull("version_state_epoch"); + instance.putNull("generation_config_revision"); + instance.putNull("remap_set_id"); + instance.putNull("script_patch_pinned_control_plane_request_id"); + instance.putNull("script_pin_epoch"); + return instance; + } + + private static ObjectNode pointer(String instanceId, String realmId) { + ObjectNode pointer = JSON.createObjectNode(); + pointer.put("id", "1"); + pointer.put("tenant_id", TENANT_ID); + pointer.put("game_instance_id", instanceId); + pointer.put("world_slug", "north-star"); + pointer.put("realm_slug", "one-realm"); + pointer.put("pointer_version", "1"); + pointer.put("catalog_revision", "1"); + pointer.put("visible", true); + pointer.put("requires_character_selection", false); + pointer.put("state_scope", "ISOLATED"); + pointer.put("character_creation_policy", "DISABLED"); + pointer.put("public_production_realm", false); + pointer.put("realm_id", realmId); + pointer.put("playable_state_namespace_id", "11111111-2222-4333-8444-555555555555"); + return pointer; + } + + private static String canonicalJson(ObjectNode projection) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)), + StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new AssertionError("Unable to build canonical snapshot test vector", exception); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationServiceTest.java new file mode 100644 index 0000000000..746e3c07de --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionRetainedTenantAssociationServiceTest.java @@ -0,0 +1,260 @@ +package unit.net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Base64; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.GameSessionTenantAssociationEvidence; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient; +import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient.LegacyGameSessionTenantAssociationReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepository.AssociationReceipt; +import net.firedevops.firemud.gamesession.service.GameSessionRetainedTenantAssociationService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.stereotype.Component; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionRetainedTenantAssociationServiceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID REQUEST = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID APPROVAL_OPERATION = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OTHER_TENANT = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String LEGACY_KEY = "42"; + + private final GameDesignRuntimeTenantIdentityClient client = + mock(GameDesignRuntimeTenantIdentityClient.class); + private final GameSessionRetainedTenantAssociationRepository repository = + mock(GameSessionRetainedTenantAssociationRepository.class); + private final PlatformTransactionManager transactionManager = + mock(PlatformTransactionManager.class); + private final GameSessionRetainedTenantAssociationService service = + new GameSessionRetainedTenantAssociationService( + client, repository, transactionManager, NAMESPACE); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesOwnerReceiptBeforeStartingReadCommittedRequiresNewTransaction() { + LegacyGameSessionTenantAssociationReceipt ownerReceipt = receipt(NAMESPACE, TENANT, 42L); + AssociationReceipt localReceipt = mock(AssociationReceipt.class); + when(client.resolveLegacyGameSessionTenantAssociation( + eq(TENANT.toString()), eq(APPROVAL_OPERATION.toString()), eq(LEGACY_KEY), anyString())) + .thenReturn(ownerReceipt); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenReturn(new SimpleTransactionStatus()); + when(repository.register(REQUEST, ownerReceipt)).thenReturn(localReceipt); + + assertThat( + service.associate( + REQUEST.toString(), TENANT.toString(), APPROVAL_OPERATION.toString(), LEGACY_KEY)) + .isSameAs(localReceipt); + + InOrder ordered = inOrder(client, transactionManager, repository); + ordered + .verify(client) + .resolveLegacyGameSessionTenantAssociation( + eq(TENANT.toString()), eq(APPROVAL_OPERATION.toString()), eq(LEGACY_KEY), anyString()); + ArgumentCaptor definition = + ArgumentCaptor.forClass(TransactionDefinition.class); + ordered.verify(transactionManager).getTransaction(definition.capture()); + ordered.verify(repository).register(REQUEST, ownerReceipt); + ordered.verify(transactionManager).commit(any(TransactionStatus.class)); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + + ArgumentCaptor readRequest = ArgumentCaptor.forClass(String.class); + verify(client) + .resolveLegacyGameSessionTenantAssociation( + eq(TENANT.toString()), + eq(APPROVAL_OPERATION.toString()), + eq(LEGACY_KEY), + readRequest.capture()); + UUID readRequestId = UUID.fromString(readRequest.getValue()); + assertThat(readRequestId.toString()).isEqualTo(readRequest.getValue()); + assertThat(readRequestId).isNotEqualTo(REQUEST).isNotEqualTo(APPROVAL_OPERATION); + } + + @Test + void rejectsMalformedCallerBindingBeforeOwnerReadOrTransaction() { + List malformed = + List.of( + new String[] {null, TENANT.toString(), APPROVAL_OPERATION.toString(), LEGACY_KEY}, + new String[] { + new UUID(0L, 0L).toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY + }, + new String[] { + "abcdefab-cdef-4abc-8def-abcdefabcdef".toUpperCase(Locale.ROOT), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY + }, + new String[] { + REQUEST.toString(), "not-a-uuid", APPROVAL_OPERATION.toString(), LEGACY_KEY + }, + new String[] { + REQUEST.toString(), + new UUID(0L, 0L).toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY + }, + new String[] { + REQUEST.toString(), + TENANT.toString(), + "00000000-0000-0000-0000-000000000000", + LEGACY_KEY + }, + new String[] { + REQUEST.toString(), TENANT.toString(), APPROVAL_OPERATION.toString(), "0" + }, + new String[] { + REQUEST.toString(), TENANT.toString(), APPROVAL_OPERATION.toString(), "042" + }, + new String[] { + REQUEST.toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + "9223372036854775808" + }); + + for (String[] arguments : malformed) { + assertThatThrownBy( + () -> service.associate(arguments[0], arguments[1], arguments[2], arguments[3])) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(client, transactionManager, repository); + } + + @Test + void rejectsDirectInvocationInsideActualTransactionBeforeSourceRead() { + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> + service.associate( + REQUEST.toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an owner transaction"); + + verifyNoInteractions(client, transactionManager, repository); + } + + @Test + void rejectsContradictoryOwnerReceiptBeforeTransactionStart() { + when(client.resolveLegacyGameSessionTenantAssociation( + anyString(), anyString(), anyString(), anyString())) + .thenReturn(receipt("other-namespace", TENANT, 42L)) + .thenReturn(receipt(NAMESPACE, OTHER_TENANT, 42L)) + .thenReturn( + receipt( + NAMESPACE, UUID.fromString("66666666-6666-4666-8666-666666666666"), TENANT, 42L)) + .thenReturn(receipt(NAMESPACE, TENANT, 43L)); + + for (int attempt = 0; attempt < 4; attempt++) { + assertThatThrownBy( + () -> + service.associate( + REQUEST.toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match the exact association"); + } + + verify(client, times(4)) + .resolveLegacyGameSessionTenantAssociation( + eq(TENANT.toString()), eq(APPROVAL_OPERATION.toString()), eq(LEGACY_KEY), anyString()); + verifyNoInteractions(transactionManager, repository); + } + + @Test + void sourceFailureDoesNotStartTransactionOrCreateLocalState() { + when(client.resolveLegacyGameSessionTenantAssociation( + anyString(), anyString(), anyString(), anyString())) + .thenThrow(new IllegalStateException("owner unavailable")); + + assertThatThrownBy( + () -> + service.associate( + REQUEST.toString(), + TENANT.toString(), + APPROVAL_OPERATION.toString(), + LEGACY_KEY)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("owner unavailable"); + + verifyNoInteractions(transactionManager, repository); + } + + @Test + void associationCandidateIsNotRegisteredAsSpringComponent() { + assertThat( + AnnotatedElementUtils.hasAnnotation( + GameSessionRetainedTenantAssociationService.class, Component.class)) + .isFalse(); + assertThat( + AnnotatedElementUtils.hasAnnotation( + GameSessionRetainedTenantAssociationRepository.class, Component.class)) + .isFalse(); + } + + private static LegacyGameSessionTenantAssociationReceipt receipt( + String namespace, UUID canonicalTenantId, long legacyKey) { + return receipt(namespace, APPROVAL_OPERATION, canonicalTenantId, legacyKey); + } + + private static LegacyGameSessionTenantAssociationReceipt receipt( + String namespace, UUID operationId, UUID canonicalTenantId, long legacyKey) { + GameSessionTenantAssociationEvidence evidence = + new GameSessionTenantAssociationEvidence( + 1, + operationId, + namespace, + "fixture-key", + "approved-by-test", + "approval-reference-1", + "2026-01-01T00:00:00Z", + Long.toString(legacyKey), + canonicalTenantId, + "501", + "source-game-501", + "RETAINED_GAME_V30", + "sha256:" + "a".repeat(64)); + String signature = Base64.getEncoder().encodeToString(new byte[64]); + return new LegacyGameSessionTenantAssociationReceipt( + evidence, evidence.manifestDigest(), signature); + } +} From 8ea72168dc572c67a68fc034dd7bc47aff1191e0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 01:28:10 +1300 Subject: [PATCH 06/23] docs(unit1b): record executed retained association PostgreSQL proof --- .../implementation-tracking/player-access-and-session.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index af794bf8f7..6d89cc50c5 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,9 +6,13 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +Exact published receiver head `2e37b38f5fc022844f97ce654e4678771c620376` [CI36858344954](https://github.com/benhook1013/FireMUD/actions/runs/36858344954) completed FAILURE overall but passed both mandatory Game Session PostgreSQL component gates: intake5, snapshot3 and association9 all executed with zero skips/failures/errors; all seven required new snapshot/association methods executed once and passed. This proves the component source fence, exact immutable association, concurrency, lost-response retry and rollback cases that skipped locally, not a live authenticated handoff or admission. The broader Game Session check was subsequently cancelled and is not green. Evidence is the strict runner JUnit verifier output; downloaded failure artifacts are HTML, not raw JUnit XML. Game Design's dedicated association9 suite also passed. + +That exact run also failed Python lint (10 errors), the Game Design recovery-warning summary contract, Automation PostgreSQL8/69, Game Design EntityDigest duplicate9301 (1/48), and TCP cross-service13/17. The Automation null-base/compensation fixes remain absent upstream ancestry already identified below; the Game Design fixture remains routed to General. No generic flaky/inherited conclusion is inferred for the other failures. Subsequent Account UUID authentication producer edits are local and unpublished, excluded from this run; their local 481 unit executions and 146 PostgreSQL skips do not establish consumer convergence. The membership RPC, credential/context/catalog activation and ring mount remain gated. + 2026-10-02 #2923 adds the unwired Game Session owner-local receiver for the separately audited Game Design tenant association. Its closed retained identity snapshot captures all six declared source families under one short READ COMMITTED write fence, rejects incomplete pointers/backfill issues and changed source evidence, and binds the exact namespace, retained key and canonical tenant UUID. The service obtains authenticated Game Design evidence before opening that transaction; V8 then stores the complete immutable approval, snapshot, namespace-qualified one-to-one claims and exact local request/result. Lost-response recovery and exact retry return the original durable evidence without recapturing or rewriting later source state. Neither the service nor association repository is registered as a runtime bean or public route. The canonical contract is [Game Session's retained snapshot and association](../../architecture/microservices/game-session-service/api-contracts.md#retained-tenant-identity-snapshot-and-local-association). -Local Game Session full check/JAR, Java formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown passed: 123 tasks, 33 executed/90 up-to-date. Tests executed 1,747 unit cases, 18 non-PostgreSQL integration cases and one cross-service case with zero failures/errors; the nine new snapshot/service unit cases all executed. Seventeen unit, 128 integration and 33 cross-service cases skipped. The 12 new PostgreSQL cases (three snapshot-fence and nine association cases) compiled/discovered but all skipped without Docker, so source-lock, phantom exclusion, concurrent first-writer, immutable readback and rollback database behavior remain unproved on this candidate. Initial delegated import/jOOQ API compile defects and an unnecessary analyzer suppression were corrected without relaxing any assertion or transaction guard. The new early strict CI gate requires both suites and their mandatory methods before the broader check; workflow presence is not execution proof. Protected approval custody/import, live authenticated handoff, canonical catalog/carrier convergence and all runtime activation remain open. +Local Game Session full check/JAR, Java formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown passed: 123 tasks, 33 executed/90 up-to-date. Tests executed 1,747 unit cases, 18 non-PostgreSQL integration cases and one cross-service case with zero failures/errors; the nine new snapshot/service unit cases all executed. Seventeen unit, 128 integration and 33 cross-service cases skipped. The 12 new PostgreSQL cases (three snapshot-fence and nine association cases) compiled/discovered but all skipped without Docker; the exact runner execution above now supersedes that local-only database limit. Initial delegated import/jOOQ API compile defects and an unnecessary analyzer suppression were corrected without relaxing any assertion or transaction guard. The early strict CI gate requires both suites and their mandatory methods before the broader check. Protected approval custody/import, live authenticated handoff, canonical catalog/carrier convergence and all runtime activation remain open. Exact source/read candidate `2583d65671bb8f9256b1216e5cbee5fe50c3d9ff` [CI36850617996](https://github.com/benhook1013/FireMUD/actions/runs/36850617996) completed FAILURE, but its new mandatory Game Design association suite executed all nine PostgreSQL cases with zero skips/failures/errors; each of four required methods executed once and passed. Strict Game Design creation8/authored-source10, Game Session intake5 and Account JOIN/LEFT39, exchange9, issuance9, authority-generation2, outbox4, committed-source18, fresh association6, pair8 and fresh UUID snapshot11 also passed without skips/failures/errors. Counts come from the strict runner report verifier; downloaded test artifacts are HTML, not raw JUnit XML. Game Session's broader check was cancelled after intake, so no broader Script Pin/WebSocket execution is credited. These component proofs do not enable the receiver, catalog, membership RPC or credentials. From 47153d26ca38af56033962d0fc962842ddf9b7f7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 02:34:01 +1300 Subject: [PATCH 07/23] Converge Account authentication UUIDs and preserve command identity storage --- .github/workflows/ci.yml | 35 +++ .../account-service/api-contracts.md | 6 +- .../account-service/runtime-and-data.md | 2 +- .../game-session-service/runtime-and-data.md | 2 + .../platform-operations-and-delivery.md | 2 + .../player-access-and-session.md | 6 +- protos/account/v1/account_service.proto | 3 + .../controller/AccountController.java | 34 ++- .../controller/AccountRequestReaders.java | 18 ++ .../controller/ProfileController.java | 15 +- .../dto/AuthenticationResult.java | 21 +- .../service/AccountService.java | 4 + .../service/impl/AccountGrpcService.java | 39 ++- .../service/impl/AccountServiceImpl.java | 56 +++- .../src/main/resources/openapi.yaml | 34 ++- ...ountAuthenticationUuidIntegrationTest.java | 259 ++++++++++++++++++ .../controller/AccountControllerTest.java | 64 +++-- .../controller/AccountRequestReadersTest.java | 36 +++ .../controller/AuthControllerTest.java | 7 +- .../controller/ProfileControllerTest.java | 98 +++++-- .../dto/AuthenticationResultTest.java | 32 +++ .../service/impl/AccountGrpcServiceTest.java | 97 +++++-- .../service/impl/AccountServiceImplTest.java | 210 +++++++++++++- .../gamesession/entity/GameplayCommand.java | 4 + .../repository/GameplayCommandRepository.java | 3 + .../V9__gameplay_command_account_uuid.sql | 9 + ...ndAccountUuidMigrationIntegrationTest.java | 91 ++++++ ...eplayCommandRepositoryIntegrationTest.java | 83 ++++++ 28 files changed, 1127 insertions(+), 143 deletions(-) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountRequestReadersTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AuthenticationResultTest.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V9__gameplay_command_account_uuid.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ef611ff759..8b88000c37 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -988,6 +988,41 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationRepositoryIntegrationTest#concurrentExactFirstWritersReturnSameImmutableReceipt()' \ game-session-service + - name: Run Account persisted UUID authentication PostgreSQL component proof + if: ${{ matrix.module == 'account-service' }} + run: | + ./gradlew :account-service:integrationTest \ + --tests net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest \ + --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#repositoryInsertAuthenticationUsesExactPersistedUuidAndPrivateStorageKey()' \ + --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#databaseInsertAuthenticationUsesTriggerProvedUuidAndCannotRemapItsSource()' \ + --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#unmappedUuidDeniesProfileMutationEvenWhenBodyNamesAnExistingPrivateRow()' \ + account-service + + - name: Run Game Session command Account UUID storage PostgreSQL component proof + if: ${{ matrix.module == 'game-session-service' }} + run: | + ./gradlew :game-session-service:integrationTest \ + --tests net.firedevops.firemud.gamesession.repository.GameplayCommandRepositoryIntegrationTest.saveRoundTripsExplicitAccountUuidWithoutChangingLegacyNumericAccountId \ + --tests net.firedevops.firemud.gamesession.repository.GameplayCommandRepositoryIntegrationTest.saveRoundTripsNullableAccountUuidAlongsideLegacyNumericAccountId \ + --tests net.firedevops.firemud.gamesession.repository.GameplayCommandRepositoryIntegrationTest.saveRejectsNilAccountUuidAtDatabaseFence \ + --tests net.firedevops.firemud.gamesession.repository.GameplayCommandRepositoryIntegrationTest.accountUuidEvidenceInsertRollsBackWithItsContainingTransaction \ + --tests net.firedevops.firemud.gamesession.repository.GameplayCommandAccountUuidMigrationIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.gamesession.repository.GameplayCommandRepositoryIntegrationTest \ + --require-suite net.firedevops.firemud.gamesession.repository.GameplayCommandAccountUuidMigrationIntegrationTest \ + --require-case 'net.firedevops.firemud.gamesession.repository.GameplayCommandRepositoryIntegrationTest#saveRoundTripsExplicitAccountUuidWithoutChangingLegacyNumericAccountId()' \ + --require-case 'net.firedevops.firemud.gamesession.repository.GameplayCommandRepositoryIntegrationTest#saveRoundTripsNullableAccountUuidAlongsideLegacyNumericAccountId()' \ + --require-case 'net.firedevops.firemud.gamesession.repository.GameplayCommandRepositoryIntegrationTest#saveRejectsNilAccountUuidAtDatabaseFence()' \ + --require-case 'net.firedevops.firemud.gamesession.repository.GameplayCommandRepositoryIntegrationTest#accountUuidEvidenceInsertRollsBackWithItsContainingTransaction()' \ + --require-case 'net.firedevops.firemud.gamesession.repository.GameplayCommandAccountUuidMigrationIntegrationTest#migrationRetainsLegacyCommandRowsAndDoesNotInventAccountUuids()' \ + game-session-service + - name: 🧪 Run Gradle Checks id: checks run: | diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index b22cb7bf95..cef434cd22 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -60,6 +60,8 @@ The hosted Creator Party, terms catalog, acceptance/currentness evidence, and ch The current credential-granting `Authenticate`, `RequestEmailLoginOtp`, and `VerifyEmailLoginOtp` gRPC handlers require the exact authenticated Game Session mTLS peer before credential or challenge work; the shared public-method list still bypasses bearer validation for these methods, so the peer guard is required and is not a JWT fallback. Legacy profile GET/PUT now require the exact Social Groups peer and a non-internal caller subject matching the requested account; presence-policy batch reads require the exact Social Groups peer and read only tenant-scoped profiles. The account-ID export, external-link, and verification gRPC handlers deny before data access or mutation because no authorized caller contract exists. Runtime membership, grant, and entitlement methods deny before Account reads until typed player/target binding is available; these local guards are not complete admission proof. `GetBalance`, `AddCurrency`, and `SpendCurrency` now return `FAILED_PRECONDITION` before balance access or mutation because virtual currency is a deferred substrate, not a supported v1 API. +The authentication response's `accountId` is the canonical non-nil UUID required by [Identifier Glossary](../../system-architecture-identifier-glossary.md); Account must prove the exact persisted `account_uuid`, recognized provenance and unchanged numeric source row before issuing the result or consuming a successful challenge. `Authenticate`, email-OTP completion and REST `/auth/login` carry that same UUID, and the token's subject and Account identity claim carry it under the [JWT owner](../../system-architecture-jwt-and-token-contracts.md). The numeric Account primary key remains an Account-local storage selector, never an alternate wire identity. A missing or contradictory source denies credential creation; no tenant association or admission follows from proving global Account identity. The complete consumer, registry and activation proof remains separately tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + Fresh-tenant identity adds no public Account endpoint or membership shortcut. The #2915 consumer uses Account's authenticated normal workload to read exact Game Design creation evidence, then commits an immutable canonical-UUID association and shared UUID conflict claim before using the existing no-reset tenant-generation initialization; it neither infers a retained numeric key nor admits a player. Exact #2915 head `910d0a6f41d60ee7214b610d56f89c51db260413` [CI 36796087279](https://github.com/benhook1013/FireMUD/actions/runs/36796087279) executed and passed all six Account fresh-association and seven Game Design creation PostgreSQL cases without skips, including retry, concurrency and rollback. This corrected component proof supersedes the earlier schema-fixture failure; it does not prove deployed workload identity, a live cross-owner handoff or activation. Detailed proof and remaining gates belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). The Game Design wire and digest remain owned by its [API contract](../game-design-service/api-contracts.md#fresh-tenant-creation-operation-and-account-readback), and Account's local storage/readback consequence is described in [Runtime & Data](./runtime-and-data.md). The membership RPC remains denied. `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. @@ -212,7 +214,7 @@ Current recovery/verification response and delivery behavior: password-reset, us The current `POST /auth/connect-token` REST response body is metadata-only: it contains no raw connect token or internal `jti`, and no custom response header may provide one. The token is delivered only in the protected HttpOnly `Firemud-Connect-Token` `Set-Cookie` with the documented cookie security attributes. The target issuance contract makes an exact retry with the same `(accountId, connectScopeId, requestId)` and digest replay the stored result; after the response-envelope recovery horizon, a matching compact receipt returns `RESPONSE_RECOVERY_EXPIRED` and the caller must use a fresh `requestId`, while a changed digest returns `IDEMPOTENCY_CONFLICT`. That durable replay behavior is not yet implemented. No gRPC `IssueConnectToken` transport exists. -The current executable REST and internal response examples use numeric account and tenant IDs. UUID wire identities are an ADR 0020 target-state migration and are not current executable examples. +The authentication result and its Account-signed `sub`/`accountId` use the persisted canonical Account UUID. Account-qualified self-service paths and the subject-bound `GetProfile`/`UpdateProfile` request carry that UUID unchanged; Account resolves it to a private numeric row only inside its own persistence boundary after verified identity readback. Other resource DTOs, tenant selectors and legacy runtime requests still have numeric migration gaps; this correction does not establish complete cross-service UUID carriage or an enabled gameplay path. Canonical current `/auth/login` success shape: @@ -220,7 +222,7 @@ Canonical current `/auth/login` success shape: { "status": "SUCCESS", "data": { - "accountId": 42, + "accountId": "457336d4-63d7-4a3a-a481-ceecb1c8c296", "authToken": "jwt-token-here" } } diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 749c0718ef..c59ca9af9f 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -14,7 +14,7 @@ Account V22/V23 rewrite retained email values to canonical form and validate a c Account V25 enforces the live tenant-scoped profile identity `(tenantId, accountId)`. Before adding the unique constraint, the migration fails closed with the named `profiles_tenant_account_identity_collision` preflight constraint when retained duplicates exist; it does not select, merge, delete, or rewrite those rows. Focused PostgreSQL proof covers legal profiles for one global account in different tenants, same-tenant duplicate rejection, and retained-duplicate migration failure without row loss, but those cases compile and are skipped when Docker is unavailable. This current-schema correction does not resolve the separate global-registration, explicit-membership, retained tenant-default, or mixed-binary obligations. -Account V29 keeps the numeric `accounts.id` primary key and adds an immutable canonical `account_uuid` per Account. Retained rows receive `ACCOUNT_V29_MIGRATION` provenance and a source numeric row equal to their unchanged primary key; an Account insert trigger binds new rows to their numeric key, while `AccountRepository` assigns UUIDs with `ACCOUNT_REPOSITORY_INSERT` provenance and verifies exact persisted identity readback. Database uniqueness constraints prevent duplicate UUID/source mappings. This is an Account persistence bridge only: REST/gRPC DTOs, JWT identities, and external callers remain numeric, and this migration does not create or infer tenant UUID mappings. The focused repository/migration integration class compiled successfully, but all 13 cases were skipped because Docker was unavailable; V29 PostgreSQL migration and immutability behavior therefore remains unexecuted runtime proof. +Account V29 keeps the numeric `accounts.id` primary key and adds an immutable canonical `account_uuid` per Account. Retained rows receive `ACCOUNT_V29_MIGRATION` provenance and a source numeric row equal to their unchanged primary key; an Account insert trigger binds new rows to their numeric key, while `AccountRepository` assigns UUIDs with `ACCOUNT_REPOSITORY_INSERT` provenance and verifies exact persisted identity readback. Database uniqueness constraints prevent duplicate UUID/source mappings. Authentication responses and their signed Account subject now consume that persisted UUID after exact provenance/source-row checks. Account-qualified self-service selectors and subject-bound profile RPCs compare the canonical UUID before Account resolves its private row key; this lookup neither enrolls nor repairs missing identity. Other resource DTOs, bootstrap/runtime requests and cross-owner consumers still have numeric migration gaps, and this Account-local bridge creates no tenant UUID mapping. Focused migration/immutability execution and consumer limits remain in the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md); local PostgreSQL cases skip when Docker is unavailable. The current Unit 1B draft adds V31 positive authority-generation rows and an account-local issuance fence, enrolls the exact JWT issuer idempotently at startup, initializes new global Account UUID generation and fence in the registration transaction, and enrolls a canonical tenant generation only after approved retained-row association readback. V34 enrolls retained Account UUIDs into both Account generation and fence state without resetting an advanced pair; a half-pair aborts. V33 provides independently sequenced immutable authority events, and the shared closed membership-event codec has Account/Game Session canonicalization vectors. The local V36 candidate adds an Account-owned durable authority row for each verified Account/tenant pair: a never-joined pair has positive version and generation at sequence zero before JOIN, while the first JOIN advances version to two and event sequence to one without independently advancing generation. Its sequence-zero read requires pair provenance, row/receipt/event absence, and the complete tuple under one Account fence; it never grants admission. Retained positive rows can enroll only from exact current event and receipt evidence without renumbering, while contradictory or unproved inactive retained rows remain denied. The current explicit JOIN candidate composes the approved retained tenant UUID, membership generation and fence, role snapshot, canonical V33 event, receipt, audit, and terminal operation in its Account transaction; exact replay and abandoned-`PENDING` recovery require event readback. An unwired Account-owned LEFT component now transitions only an already-proved retained ACTIVE pair to retained INACTIVE state; its exact current-INACTIVE reader requires the existing pair plus matching latest positive LEFT receipt and canonical event, and it does not turn historical replay into current authority after reactivation. This component does not expose a route or caller authentication and has no executed PostgreSQL proof yet. Account runtime RPC enablement, event delivery/Redis projection, Game Session consumer, and fresh-tenant UUID handoff remain open. Neither V31/V36 enrollment nor the JOIN/LEFT-local event fences an old issuer binary or completes token issuance. V35 is an unwired Account-owned connect-issuance operation/envelope storage candidate; production issuance still uses the legacy path, and key-ring deployment and exact-result recovery proof remain open. Detailed current proof and rollout limits remain in the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md). 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 3101d7fb64..87392bf33a 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: +- V9 adds a nullable, non-nil `gameplay_command.account_uuid` storage slot and exact repository readback for a verified producer's canonical Account identity. It preserves the complete existing row and numeric `account_id` evidence without deriving or backfilling a UUID. The current command ingress still uses its older carrier until the consumer correction is integrated; retained rows without authenticated mapping cannot become canonical UUID evidence. Storage availability alone does not prove caller authorization, retained-command replay, or activation of the denied credential and membership paths. + - The shared Gateway connect-context codec now declares and verifies the complete signed-context shape and has local vectors, but first-party runtime parsing remains fail-closed. It does not admit the target context until the independent Gateway Ed25519 verification key is published, Account-to-tenant UUID mapping is available, and the real Account exchange/source-evidence path is proved. Codec and vector presence is not a live issuer/consumer handoff or gameplay-admission proof. - The Account membership client rejects noncanonical, nil or numeric Account/tenant selectors before stub/channel use and preserves exact UUID request echoes. This is boundary validation, not Account authorization. The current numeric session/catalog carriers still lack the proved canonical UUID handoff required by the [Identifier Glossary](../../system-architecture-identifier-glossary.md#identifier-format-conventions); numeric stringification cannot satisfy that handoff. The complete signed-context parser, Account runtime RPC and credential producer remain denied; component and runtime proof are tracked in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index b0970e9d6f..b41d021269 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -227,6 +227,8 @@ These are repository-recorded proofs, not a claim that the tracker consolidation - [ADR 0073](../../architecture/decisions/adr-0073-evidence-calibrated-tick-budgets-and-lock-ttls.md) keeps bootstrap timing formulas separate from measured production safety settings; current operator/configuration surfaces do not yet prove evidence-calibrated values or the complete lease/cleanup health split. - Account response-envelope ring delivery remains blocked at the authenticated handoff boundary. The local [source bootstrap](../../../dev-tools/deploy/bootstrap-account-response-envelope-ring.py) and [Secret materializer](../../../dev-tools/deploy/materialize-account-response-envelope-ring.py), with focused [materializer tests](../../../dev-tools/tests/test_account_response_envelope_materializer.py), cover protected-source generation/predecessor checks, authenticated Kubernetes username lookup, CAS create/replace, post-write Secret UID/resourceVersion readback, and the distinct typed `account-response-envelope-ring-materialization-v1` receipt. They do not implement or prove an authenticated owner publisher, durable content-addressed source/receipt store, or receipt publish/readback consumer; the local verifier checks structure and caller-supplied bindings, not transport or publisher authentication, and a Git projection is not that handoff. The local receipt operation now identifies only the source transition (`create` for a null predecessor, `rotate` otherwise); invocation-local retry no longer changes canonical receipt bytes/digest, and the strict verifier rejects retry and operation/predecessor mismatch. Focused tests assert create/retry, rotate/retry, and lost-result retry equality with no second Secret write. These equalities apply only to unchanged exact source generation, predecessor, manifest, authenticated materializer, Secret UID/resourceVersion, and freshness annotations; an actual changed readback remains a mismatch, not retry authorization. Keep the ring mount unpublished and Account envelope purposes disabled until source custody, sole-writer enforcement, authenticated receipt publication/readback, deployment readback, and separate live freshness/readiness gates are proved. This receipt remains distinct from `jwt-signing-keys-jwks`; do not couple ring activation to JWT/JWKS evidence. +The bounded automated ring-delivery implementation proposal uses a dedicated environment-owned S3-compatible store, separate from backups, for the protected create-once source generations and immutable content-addressed non-secret receipts. A scoped authenticated environment/secrets publisher would publish exact generation/predecessor evidence and a compare-and-set current pointer; the sole Kubernetes Secret materializer and authenticated read-only consumers remain separate identities. No such publisher identity, source store or authenticated receipt endpoint is currently provisioned. Source custody, immutable/CAS retry and concurrency behavior, publisher authentication, exact Secret UID/resourceVersion readback, and independent live freshness/readiness need executable proof before mount publication; Kubernetes `resourceNames` restrictions alone cannot establish exclusive Secret creation. This is an implementation proposal for the existing [environment/secrets handoff contract](../../architecture/infrastructure/environment-and-secrets-overview.md), not executed infrastructure or replacement JWT/JWKS evidence. + ## To Discuss No competing target state is recorded for bounded metrics, curated edge routing, external deadman authority, manifest-owned binding identity, or canonical reset tooling. Design decisions remain required before: choosing between retaining the preview-only bootstrap session and replacing it with a first-party TCP admission path; defining richer Kubernetes live-state preflight; defining automated JWT/JWKS rotation; selecting one canonical current-region source for broad `regionId` gameplay-log enrichment; approving any metrics-label exception; or adding a new public route class. The opaque external-monitor `evidenceRef`/`checkRef` contract also leaves contemporaneous evidence selection with the environment/operator boundary. 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 6d89cc50c5..bea7d5acdc 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,9 +6,13 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The Account authentication producer now returns its exact persisted canonical non-nil UUID and signs that same identity in `sub`/`accountId` for password and email-OTP paths. Profile and supported self-service readers first bind the canonical UUID to the authenticated subject, then perform an Account-owned read-only provenance-checked lookup of the private numeric storage key; an unmapped UUID cannot select or mutate another row. Disabled deletion, login-factor mutation and tenant export remain denied without writes. Other numeric DTO, catalog and cross-service consumers are explicitly unfinished; this component does not establish a working end-to-end login/admission path. Game Session V9 separately adds exact command UUID storage without altering or inventing identities for retained numeric rows. The consumer-carrier correction remains a separate unpublished candidate. + +Local consolidated Account/Game Session full checks and JARs passed (156 tasks, 72 executed/84 up-to-date), including formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown. Account's 502 unit cases passed in the preceding same-code execution; their final task was up-to-date, not a second execution. All 149 Account PostgreSQL cases compiled/discovered and skipped without Docker, including the three new persisted-identity/profile no-mutation cases. Game Session executed 1,747 unit, 18 non-PostgreSQL integration and one cross-service case; 17 unit, 133 integration and 33 cross-service cases skipped, including five new command-storage/migration cases. Strict CI component gates now require all eight new cases to execute, but have not yet supplied runner proof for this correction. The earlier possible-null integration fixture readback defect was corrected with explicit required-row checks, not an analyzer suppression. Ring publication infrastructure is an open Platform Operations prerequisite; its mount and all previously denied activation paths remain held back. + Exact published receiver head `2e37b38f5fc022844f97ce654e4678771c620376` [CI36858344954](https://github.com/benhook1013/FireMUD/actions/runs/36858344954) completed FAILURE overall but passed both mandatory Game Session PostgreSQL component gates: intake5, snapshot3 and association9 all executed with zero skips/failures/errors; all seven required new snapshot/association methods executed once and passed. This proves the component source fence, exact immutable association, concurrency, lost-response retry and rollback cases that skipped locally, not a live authenticated handoff or admission. The broader Game Session check was subsequently cancelled and is not green. Evidence is the strict runner JUnit verifier output; downloaded failure artifacts are HTML, not raw JUnit XML. Game Design's dedicated association9 suite also passed. -That exact run also failed Python lint (10 errors), the Game Design recovery-warning summary contract, Automation PostgreSQL8/69, Game Design EntityDigest duplicate9301 (1/48), and TCP cross-service13/17. The Automation null-base/compensation fixes remain absent upstream ancestry already identified below; the Game Design fixture remains routed to General. No generic flaky/inherited conclusion is inferred for the other failures. Subsequent Account UUID authentication producer edits are local and unpublished, excluded from this run; their local 481 unit executions and 146 PostgreSQL skips do not establish consumer convergence. The membership RPC, credential/context/catalog activation and ring mount remain gated. +That exact run also failed Python lint (10 errors), the Game Design recovery-warning summary contract, Automation PostgreSQL8/69, Game Design EntityDigest duplicate9301 (1/48), and TCP cross-service13/17. The Automation null-base/compensation fixes remain absent upstream ancestry already identified below; the Game Design fixture remains routed to General. No generic flaky/inherited conclusion is inferred for the other failures. Subsequent Account UUID authentication corrections above are excluded from that historical run and do not establish consumer convergence. The membership RPC, credential/context/catalog activation and ring mount remain gated. 2026-10-02 #2923 adds the unwired Game Session owner-local receiver for the separately audited Game Design tenant association. Its closed retained identity snapshot captures all six declared source families under one short READ COMMITTED write fence, rejects incomplete pointers/backfill issues and changed source evidence, and binds the exact namespace, retained key and canonical tenant UUID. The service obtains authenticated Game Design evidence before opening that transaction; V8 then stores the complete immutable approval, snapshot, namespace-qualified one-to-one claims and exact local request/result. Lost-response recovery and exact retry return the original durable evidence without recapturing or rewriting later source state. Neither the service nor association repository is registered as a runtime bean or public route. The canonical contract is [Game Session's retained snapshot and association](../../architecture/microservices/game-session-service/api-contracts.md#retained-tenant-identity-snapshot-and-local-association). diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index c4976178fa..8de04ec592 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -114,6 +114,7 @@ message AuthenticateRequest { message AuthenticateResponse { string auth_token = 1; + // Canonical non-nil Account UUID from the authenticated persisted source row, never its numeric PK. string account_id = 2; shared.v1.ErrorDetail error = 3; } @@ -261,6 +262,7 @@ message GetTenantEntitlementsForRuntimeResponse { message GetProfileRequest { string tenant_id = 1; + // Canonical non-nil Account UUID, exactly matching the authenticated caller subject. string account_id = 2; } @@ -287,6 +289,7 @@ message ListPresenceVisibilityPoliciesResponse { message UpdateProfileRequest { string tenant_id = 1; + // Canonical non-nil Account UUID, exactly matching the authenticated caller subject. string account_id = 2; string profile_json = 3; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java index dc11b8e3cd..b263e18055 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java @@ -2,6 +2,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import jakarta.validation.Valid; +import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountDataExportDto; import net.firedevops.firemud.accountservice.dto.AccountDto; import net.firedevops.firemud.accountservice.dto.AccountLoginAuthModesDto; @@ -45,8 +46,9 @@ public ResponseEntity> createAccount( @GetMapping("/{accountId}/login-auth-modes") public ResponseEntity> getLoginAuthModes( @PathVariable String accountId) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); - requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); + requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountUuid); + Long parsedAccountId = accountService.resolveAccountStorageId(parsedAccountUuid); return ResponseEntity.ok( ApiResponse.success(accountService.getLoginAuthModes(parsedAccountId))); } @@ -55,8 +57,8 @@ public ResponseEntity> getLoginAuthModes( public ResponseEntity> updateLoginAuthModes( @PathVariable String accountId, @Valid @RequestBody UpdateAccountLoginAuthModesRequest request) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); - requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); + requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountUuid); throw new org.springframework.web.server.ResponseStatusException( HttpStatus.NOT_IMPLEMENTED, "Recent ordinary reauthentication is required; login-factor changes are unavailable until Account implements its evidence mechanism"); @@ -65,8 +67,9 @@ public ResponseEntity> updateLoginAuthMode @GetMapping("/{accountId}/export") public ResponseEntity> exportAccount( @PathVariable String accountId) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); - requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); + requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountUuid); + Long parsedAccountId = accountService.resolveAccountStorageId(parsedAccountUuid); AccountDataExportDto data = accountService.exportAccountData(parsedAccountId); return ResponseEntity.ok(ApiResponse.success(data)); } @@ -74,9 +77,12 @@ public ResponseEntity> exportAccount( @GetMapping("/{accountId}/tenant-export") public ResponseEntity> exportTenantData( @PathVariable String accountId, @RequestParam String tenantId) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); long parsedTenantId = AccountRequestReaders.requireTenantId(tenantId); - SessionContext.requireAccountAccess(parsedTenantId, parsedAccountId); + if (!isCurrentAccount(parsedAccountUuid) && !SessionContext.hasTenantAccess(parsedTenantId)) { + throw new org.springframework.web.server.ResponseStatusException( + HttpStatus.FORBIDDEN, "Account access required"); + } throw new org.springframework.web.server.ResponseStatusException( HttpStatus.NOT_IMPLEMENTED, "Tenant-admin export is unavailable until the tenant-wide export contract is implemented"); @@ -84,18 +90,22 @@ public ResponseEntity> exportTenantData( @DeleteMapping("/{accountId}") public ResponseEntity> deleteAccount(@PathVariable String accountId) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); - requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); + requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountUuid); throw new net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException( "ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE", "Account deletion is unavailable until its provider reconciliation and data retention workflow is implemented"); } - private void requireCurrentAccountOrGlobalPrivilegedRole(Long accountId) { - if (SessionContext.isCurrentAccount(accountId) || SessionContext.hasGlobalPrivilegedRole()) { + private void requireCurrentAccountOrGlobalPrivilegedRole(UUID accountUuid) { + if (isCurrentAccount(accountUuid) || SessionContext.hasGlobalPrivilegedRole()) { return; } throw new org.springframework.web.server.ResponseStatusException( org.springframework.http.HttpStatus.FORBIDDEN, "Account access required"); } + + private static boolean isCurrentAccount(UUID accountUuid) { + return accountUuid.toString().equals(SessionContext.getAccountId()); + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountRequestReaders.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountRequestReaders.java index b328921644..3608a1a482 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountRequestReaders.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountRequestReaders.java @@ -1,10 +1,28 @@ package net.firedevops.firemud.accountservice.controller; +import java.util.UUID; import net.firedevops.firemud.common.security.RequestIdValidation; final class AccountRequestReaders { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private AccountRequestReaders() {} + static UUID requireAccountUuid(String accountId) { + if (accountId == null || accountId.isBlank()) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + try { + UUID parsed = UUID.fromString(accountId); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(accountId)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID", exception); + } + } + static long requireAccountId(String accountId) { return RequestIdValidation.requirePositiveLong(accountId, "accountId"); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java index b0bc7c1015..eb2626c23a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java @@ -2,6 +2,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import jakarta.validation.Valid; +import java.util.UUID; import net.firedevops.firemud.accountservice.dto.ProfileDto; import net.firedevops.firemud.accountservice.dto.UpdateProfileRequest; import net.firedevops.firemud.accountservice.service.AccountService; @@ -33,9 +34,10 @@ public ProfileController(AccountService accountService) { @GetMapping("/{accountId}") public ResponseEntity> getProfile( @PathVariable String accountId, @RequestParam String tenantId) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); long parsedTenantId = AccountRequestReaders.requireTenantId(tenantId); - requireProfileOwner(parsedAccountId); + requireProfileOwner(parsedAccountUuid); + Long parsedAccountId = accountService.resolveAccountStorageId(parsedAccountUuid); ProfileDto dto = accountService.getProfile(parsedTenantId, parsedAccountId); return ResponseEntity.ok(ApiResponse.success(dto)); } @@ -43,13 +45,14 @@ public ResponseEntity> getProfile( @PutMapping("/{accountId}") public ResponseEntity> updateProfile( @PathVariable String accountId, @Valid @RequestBody UpdateProfileRequest request) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); + UUID parsedAccountUuid = AccountRequestReaders.requireAccountUuid(accountId); long parsedTenantId = AccountRequestReaders.requireTenantId(request.tenantId()); - requireProfileOwner(parsedAccountId); + requireProfileOwner(parsedAccountUuid); if (request.presenceVisibilityPolicy() == null) { throw new IllegalArgumentException("presenceVisibilityPolicy must be provided"); } request.presenceVisibilityPolicy().requireSelectableByAccountHolder(); + Long parsedAccountId = accountService.resolveAccountStorageId(parsedAccountUuid); ProfileDto dto = accountService.updateProfile( new UpdateProfileRequest( @@ -61,8 +64,8 @@ public ResponseEntity> updateProfile( return ResponseEntity.ok(ApiResponse.success(dto)); } - private static void requireProfileOwner(long accountId) { - if (!SessionContext.isCurrentAccount(accountId)) { + private static void requireProfileOwner(UUID accountUuid) { + if (!accountUuid.toString().equals(SessionContext.getAccountId())) { throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Profile access required"); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AuthenticationResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AuthenticationResult.java index 978306a52f..3d92b74d02 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AuthenticationResult.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AuthenticationResult.java @@ -1,4 +1,23 @@ package net.firedevops.firemud.accountservice.dto; +import java.util.UUID; + /** Result of a successful authentication attempt. */ -public record AuthenticationResult(long accountId, String authToken) {} +public record AuthenticationResult(String accountId, String authToken) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public AuthenticationResult { + if (accountId == null) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + UUID parsedAccountId; + try { + parsedAccountId = UUID.fromString(accountId); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID", exception); + } + if (parsedAccountId.equals(NIL_UUID) || !parsedAccountId.toString().equals(accountId)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java index c3d2909abc..f55e8f7d1c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.accountservice.service; +import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountDataExportDto; import net.firedevops.firemud.accountservice.dto.AccountDto; import net.firedevops.firemud.accountservice.dto.AccountLoginAuthModesDto; @@ -73,6 +74,9 @@ RealmAccessGrantResult getRealmAccessGrantForRuntime( RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, String requestId); + /** Resolves a proved canonical Account UUID to its private Account-local storage key. */ + Long resolveAccountStorageId(UUID accountUuid); + ProfileDto getProfile(Long tenantId, Long accountId); java.util.Map listPresenceVisibilityPolicies( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 57d280b910..b17187ccac 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -225,22 +225,31 @@ private void requireSocialGroupsPeer() { } } - private void requireCallerAccountSubject(long accountId) { + private void requireCallerAccountSubject(UUID accountUuid) { if (SessionContext.isInternalService()) { throw new AdminAuthorizationException("Authenticated account subject is required"); } - Long callerAccountId; - try { - callerAccountId = SessionContext.currentAccountIdOrNull(); - } catch (IllegalArgumentException ex) { - throw new AdminAuthorizationException("Authenticated account subject is required"); - } - if (callerAccountId == null || callerAccountId.longValue() != accountId) { + if (!accountUuid.toString().equals(SessionContext.getAccountId())) { throw new AdminAuthorizationException("Profile access is restricted to the caller account"); } } + private static UUID requireCanonicalAccountUuid(String value) { + if (!hasText(value)) { + throw new InvalidRequestException("accountId must be a canonical non-nil UUID", null); + } + try { + UUID accountUuid = UUID.fromString(value); + if (accountUuid.equals(new UUID(0L, 0L)) || !accountUuid.toString().equals(value)) { + throw new IllegalArgumentException("accountId must be a canonical non-nil UUID"); + } + return accountUuid; + } catch (IllegalArgumentException exception) { + throw new InvalidRequestException("accountId must be a canonical non-nil UUID", exception); + } + } + private DirectTextCallerContext directTextCaller( net.firedevops.firemud.shared.v1.PlayerExecutionContext context) { return new DirectTextCallerContext( @@ -331,7 +340,7 @@ public void authenticate( AuthenticateResponse response = AuthenticateResponse.newBuilder() .setAuthToken(result.authToken()) - .setAccountId(String.valueOf(result.accountId())) + .setAccountId(result.accountId()) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); @@ -399,7 +408,7 @@ public void verifyEmailLoginOtp( responseObserver.onNext( AuthenticateResponse.newBuilder() .setAuthToken(result.authToken()) - .setAccountId(String.valueOf(result.accountId())) + .setAccountId(result.accountId()) .build()); } catch (AdminAuthorizationException ex) { responseObserver.onNext( @@ -790,8 +799,9 @@ public void getProfile( try { requireSocialGroupsPeer(); long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); - long accountId = requirePositiveRequestId(request.getAccountId(), "accountId"); - requireCallerAccountSubject(accountId); + UUID accountUuid = requireCanonicalAccountUuid(request.getAccountId()); + requireCallerAccountSubject(accountUuid); + long accountId = accountService.resolveAccountStorageId(accountUuid); var dto = accountService.getProfile(tenantId, accountId); GetProfileResponse response = GetProfileResponse.newBuilder() @@ -889,8 +899,9 @@ public void updateProfile( try { requireSocialGroupsPeer(); long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); - long accountId = requirePositiveRequestId(request.getAccountId(), "accountId"); - requireCallerAccountSubject(accountId); + UUID accountUuid = requireCanonicalAccountUuid(request.getAccountId()); + requireCallerAccountSubject(accountUuid); + long accountId = accountService.resolveAccountStorageId(accountUuid); JsonNode node = JsonMapper.builder().build().readTree(request.getProfileJson()); String displayName = node.path("displayName").asText(null); String bio = node.path("bio").asText(null); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 29c1e44a2a..f1add695d8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -128,6 +128,7 @@ public class AccountServiceImpl implements AccountService { public static final String ACCOUNT_JWT_ISSUER = "firemud-account-service"; private static final String GAMEPLAY_DELEGATION_AUDIENCE = "account-service"; private static final int EMAIL_LOGIN_OTP_MAX_ATTEMPTS = 5; + private static final UUID NIL_ACCOUNT_UUID = new UUID(0L, 0L); private static final SecureRandom EMAIL_LOGIN_OTP_RANDOM = new SecureRandom(); private static final JsonMapper AUDIT_JSON = JsonMapper.builder().build(); @@ -259,7 +260,9 @@ public AccountDto createAccount(CreateAccountRequest request) { private void requireCanonicalPersistedIdentity(Account account) { if (account == null || account.getId() == null + || account.getId() <= 0L || account.getAccountUuid() == null + || NIL_ACCOUNT_UUID.equals(account.getAccountUuid()) || account.getAccountUuidProvenance() != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT || !account.getId().equals(account.getAccountUuidSourceNumericId())) { throw new IllegalStateException( @@ -267,6 +270,24 @@ private void requireCanonicalPersistedIdentity(Account account) { } } + private void requireAuthenticationPersistedIdentity(Account account) { + AccountIdentityProvenance provenance = + account == null ? null : account.getAccountUuidProvenance(); + if (account == null + || account.getId() == null + || account.getId() <= 0L + || account.getAccountUuid() == null + || NIL_ACCOUNT_UUID.equals(account.getAccountUuid()) + || account.getAccountUuidSourceNumericId() == null + || !account.getId().equals(account.getAccountUuidSourceNumericId()) + || (provenance != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + && provenance != AccountIdentityProvenance.ACCOUNT_V29_MIGRATION + && provenance != AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT)) { + throw new IllegalStateException( + "Account UUID readback did not match its exact persisted source row"); + } + } + @Override @Transactional @Timed(value = "account.authenticate") @@ -274,16 +295,17 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult authentica String username, String password) { PrimaryAuthentication authentication = authenticateAccountIdentity(username, password, true); Account account = authentication.account(); + requireAuthenticationPersistedIdentity(account); authentication.emailLoginChallenge().ifPresent(accountEmailLoginChallengeRepository::delete); String token = mintToken( - account.getId().toString(), + account.getAccountUuid().toString(), jwtAuthProperties.getJwtExpirationMs(), authenticationTokenClaims("control-ui", account)); sessionService.storeAccountSession( account.getId(), token, jwtAuthProperties.getJwtExpirationMs()); return new net.firedevops.firemud.accountservice.dto.AuthenticationResult( - account.getId(), token); + account.getAccountUuid().toString(), token); } @Override @@ -298,16 +320,17 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult authentica PrimaryAuthentication authentication = authenticateAccountIdentity(gameplayAccount, password, true); Account account = authentication.account(); + requireAuthenticationPersistedIdentity(account); authentication.emailLoginChallenge().ifPresent(accountEmailLoginChallengeRepository::delete); String token = mintToken( - account.getId().toString(), + account.getAccountUuid().toString(), jwtAuthProperties.getJwtExpirationMs(), authenticationTokenClaims(GAMEPLAY_DELEGATION_AUDIENCE, account)); sessionService.storeAccountSession( account.getId(), token, jwtAuthProperties.getJwtExpirationMs()); return new net.firedevops.firemud.accountservice.dto.AuthenticationResult( - account.getId(), token); + account.getAccountUuid().toString(), token); } @Override @@ -372,16 +395,17 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult verifyEmai throw invalidCredentials(); } requireAuthenticationEligible(account); + requireAuthenticationPersistedIdentity(account); accountEmailLoginChallengeRepository.delete(challenge); String token = mintToken( - account.getId().toString(), + account.getAccountUuid().toString(), jwtAuthProperties.getJwtExpirationMs(), authenticationTokenClaims(GAMEPLAY_DELEGATION_AUDIENCE, account)); sessionService.storeAccountSession( account.getId(), token, jwtAuthProperties.getJwtExpirationMs()); return new net.firedevops.firemud.accountservice.dto.AuthenticationResult( - account.getId(), token); + account.getAccountUuid().toString(), token); } @Override @@ -1905,7 +1929,7 @@ private Map authenticationTokenClaims(String audience, Account a "aud", audience, "accountId", - account.getId(), + account.getAccountUuid().toString(), "globalRoles", globalRoles, "jti", @@ -1962,6 +1986,24 @@ private boolean isPublicJoinAllowedStatus(String status) { }; } + @Override + @Transactional(readOnly = true) + public Long resolveAccountStorageId(UUID accountUuid) { + if (accountUuid == null || NIL_ACCOUNT_UUID.equals(accountUuid)) { + throw new IllegalArgumentException("A canonical non-nil Account UUID is required"); + } + Account account = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow(() -> new IllegalArgumentException("Account not found")); + requireAuthenticationPersistedIdentity(account); + if (!accountUuid.equals(account.getAccountUuid())) { + throw new IllegalStateException( + "Account UUID readback did not match the requested persisted identity"); + } + return account.getId(); + } + @Override @Transactional(readOnly = true) @Timed(value = "account.get_profile") diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index b0c84028d3..d2032f141e 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -94,9 +94,12 @@ components: type: object properties: accountId: - type: integer + type: string + format: uuid + description: Canonical non-nil Account-owned UUID read back from the authenticated source row; never the numeric database primary key. authToken: type: string + required: [accountId, authToken] PlayerBootstrapResult: type: object properties: @@ -633,7 +636,8 @@ paths: in: path required: true schema: - type: integer + type: string + format: uuid responses: '200': description: Exported data @@ -649,6 +653,7 @@ paths: required: true schema: type: string + format: uuid responses: '200': description: Allowed login mechanisms @@ -669,6 +674,7 @@ paths: required: true schema: type: string + format: uuid requestBody: required: true content: @@ -684,37 +690,39 @@ paths: description: Recent ordinary reauthentication is required, but this mutation is unavailable until Account implements its evidence mechanism /accounts/{accountId}/tenant-export: get: - summary: Export tenant-scoped account data + summary: Tenant-scoped export (currently unavailable) operationId: exportTenantData parameters: - name: accountId in: path required: true schema: - type: integer + type: string + format: uuid - name: tenantId in: query required: true schema: type: string responses: - '200': - description: Exported tenant data + '501': + description: Tenant-admin export is unavailable before any account or tenant data read '400': description: Invalid account or tenant ID /accounts/{accountId}: delete: - summary: Delete global account after billing preconditions pass + summary: Global account deletion (currently unavailable before mutation) operationId: deleteAccount parameters: - name: accountId in: path required: true schema: - type: integer + type: string + format: uuid responses: - '200': - description: Deletion success + '409': + description: ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE; no mutation '400': description: Invalid account ID /profiles/{accountId}: @@ -726,7 +734,8 @@ paths: in: path required: true schema: - type: integer + type: string + format: uuid - name: tenantId in: query required: true @@ -749,7 +758,8 @@ paths: in: path required: true schema: - type: integer + type: string + format: uuid requestBody: required: true content: diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java new file mode 100644 index 0000000000..1b4ee5ef07 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java @@ -0,0 +1,259 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.doAnswer; + +import de.mkammerer.argon2.Argon2; +import de.mkammerer.argon2.Argon2Factory; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.AccountServiceApplication; +import net.firedevops.firemud.accountservice.client.EntityManagementClient; +import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.controller.ProfileController; +import net.firedevops.firemud.accountservice.dto.AuthenticationResult; +import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.UpdateProfileRequest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; +import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.session.SessionService; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.test.GatewayTestProperties; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.DSLContext; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.NONE, + classes = AccountServiceApplication.class, + properties = { + GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, + GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, + GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, + GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH, + "firemud.grpc.workload-namespace=account-auth-uuid-test" + }) +class AccountAuthenticationUuidIntegrationTest { + private static final String PASSWORD = "account-auth-test-password"; + private static final long PROFILE_TENANT_ID = 98123L; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService(registry, postgres, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private AccountService accountService; + @Autowired private AccountRepository accountRepository; + @Autowired private SessionService sessionService; + @Autowired private JwtUtil jwtUtil; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + @MockitoBean private NotificationService notificationService; + @MockitoSpyBean private AccountEmailLoginChallengeRepository challengeRepositorySpy; + + @BeforeEach + void cleanDatabaseAndObserveOwnerTransaction() { + dsl.execute("TRUNCATE TABLE account_audit_outbox"); + dsl.execute("TRUNCATE TABLE accounts RESTART IDENTITY CASCADE"); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + invocation.callRealMethod(); + return null; + }) + .when(challengeRepositorySpy) + .lockAccountChallenge(anyLong()); + } + + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void repositoryInsertAuthenticationUsesExactPersistedUuidAndPrivateStorageKey() { + String suffix = UUID.randomUUID().toString(); + String username = "repo-" + suffix; + String email = username + "@example.com"; + var created = accountService.createAccount(new CreateAccountRequest(username, email, PASSWORD)); + Account persisted = accountRepository.findById(created.id()).orElseThrow(); + + assertThat(persisted.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(persisted.getAccountUuidSourceNumericId()).isEqualTo(created.id()); + + assertAuthenticationAndPrivateLookup(username, created.id(), persisted.getAccountUuid()); + } + + @Test + void databaseInsertAuthenticationUsesTriggerProvedUuidAndCannotRemapItsSource() { + String suffix = UUID.randomUUID().toString(); + String username = "db-" + suffix; + String email = username + "@example.com"; + Long accountId = + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash, login_auth_modes) " + + "VALUES (?, ?, ?, 'PASSWORD,EMAIL_OTP') RETURNING id", + username, + email, + hashPassword(PASSWORD)) + .fetchOne(0, Long.class); + Account persisted = accountRepository.findById(accountId).orElseThrow(); + UUID accountUuid = persisted.getAccountUuid(); + + assertThat(accountUuid).isNotNull(); + assertThat(persisted.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT); + assertThat(persisted.getAccountUuidSourceNumericId()).isEqualTo(accountId); + + assertAuthenticationAndPrivateLookup(username, accountId, accountUuid); + + UUID attemptedReplacement = UUID.randomUUID(); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE accounts SET account_uuid = ? WHERE id = ?", + attemptedReplacement, + accountId)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Account identity cannot be reassigned"); + + assertThat(accountUuidFor(accountId)).isEqualTo(accountUuid); + assertThat(accountService.resolveAccountStorageId(accountUuid)).isEqualTo(accountId); + assertThatThrownBy(() -> accountService.resolveAccountStorageId(attemptedReplacement)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Account not found"); + } + + @Test + void unmappedUuidDeniesProfileMutationEvenWhenBodyNamesAnExistingPrivateRow() { + String suffix = UUID.randomUUID().toString(); + String username = "profile-" + suffix; + String email = username + "@example.com"; + var created = accountService.createAccount(new CreateAccountRequest(username, email, PASSWORD)); + dsl.execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, TRUE, 'ACTIVE', 1, 1, 'EXPLICIT_JOIN')", + created.id(), + PROFILE_TENANT_ID); + dsl.execute( + "INSERT INTO profiles (account_id, tenant_id, display_name, bio) VALUES (?, ?, ?, ?)", + created.id(), + PROFILE_TENANT_ID, + "original-display-name", + "original-bio"); + String profileBefore = profileRowJson(created.id()); + + UUID unmappedUuid = UUID.randomUUID(); + String testToken = + jwtUtil.generateToken( + unmappedUuid.toString(), Map.of("accountId", unmappedUuid.toString())); + String decodedAccountId = + jwtUtil.parseToken(testToken).getPayload().get("accountId", String.class); + SessionContext.setContext(decodedAccountId, List.of(), Map.of()); + ProfileController controller = new ProfileController(accountService); + UpdateProfileRequest request = + new UpdateProfileRequest( + PROFILE_TENANT_ID, + created.id(), + "must-not-be-written", + "must-not-be-written", + ProfilePresenceVisibilityPolicy.PRIVATE); + + assertThatThrownBy(() -> controller.updateProfile(unmappedUuid.toString(), request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Account not found"); + + assertThat(profileRowJson(created.id())).isEqualTo(profileBefore); + } + + private void assertAuthenticationAndPrivateLookup( + String username, long accountId, UUID expectedAccountUuid) { + AuthenticationResult result = accountService.authenticate(username, PASSWORD); + var claims = jwtUtil.parseToken(result.authToken()).getPayload(); + + assertThat(result.accountId()).isEqualTo(expectedAccountUuid.toString()); + assertThat(result.accountId()).isNotEqualTo(Long.toString(accountId)); + assertThat(claims.getSubject()).isEqualTo(expectedAccountUuid.toString()); + assertThat(claims.get("accountId", String.class)).isEqualTo(expectedAccountUuid.toString()); + assertThat(claims.get("tenantId")).isNull(); + assertThat(sessionService.isAccountSessionActive(accountId, result.authToken())).isTrue(); + + Account found = accountRepository.findByAccountUuid(expectedAccountUuid).orElseThrow(); + assertThat(found.getId()).isEqualTo(accountId); + assertThat(found.getAccountUuid()).isEqualTo(expectedAccountUuid); + assertThat(found.getAccountUuidSourceNumericId()).isEqualTo(accountId); + assertThat(accountService.resolveAccountStorageId(expectedAccountUuid)).isEqualTo(accountId); + assertThat(accountUuidFor(accountId)).isEqualTo(expectedAccountUuid); + } + + private UUID accountUuidFor(long accountId) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT account_uuid FROM accounts WHERE id = ?", accountId), + "Expected persisted account_uuid row for account id " + accountId) + .get(0, UUID.class); + } + + private String profileRowJson(long accountId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(p)::text FROM profiles p WHERE account_id = ? AND tenant_id = ?", + accountId, + PROFILE_TENANT_ID), + "Expected profile row for account id " + + accountId + + " and tenant id " + + PROFILE_TENANT_ID) + .get(0, String.class); + } + + private static String hashPassword(String password) { + Argon2 argon2 = Argon2Factory.create(); + char[] chars = password.toCharArray(); + try { + return argon2.hash(2, 65536, 1, chars); + } finally { + argon2.wipeArray(chars); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java index 8542656a96..477723f3b7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java @@ -13,6 +13,7 @@ import java.util.List; import java.util.Map; +import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountDataExportDto; import net.firedevops.firemud.accountservice.dto.AccountDto; import net.firedevops.firemud.accountservice.dto.AccountLoginAuthModesDto; @@ -49,6 +50,8 @@ "firemud.auth.http.public-routes[1].path-pattern=/accounts/" }) class AccountControllerTest { + private static final String ACCOUNT_UUID = "550e8400-e29b-41d4-a716-446655440000"; + private static final String OTHER_ACCOUNT_UUID = "550e8400-e29b-41d4-a716-446655440001"; @Autowired private MockMvc mockMvc; private final ObjectMapper objectMapper = new ObjectMapper(); @@ -113,7 +116,9 @@ void deleteAccountDeniesPlatformAdminBeforeServiceMutation() throws Exception { String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); mockMvc - .perform(delete("/accounts/42").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .perform( + delete("/accounts/" + ACCOUNT_UUID) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isConflict()) .andExpect(jsonPath("$.error.code").value("ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE")); @@ -126,7 +131,9 @@ void deleteAccountRejectsScopedTenantAdminBecauseFullDeletionIsAccountScoped() t jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("7", List.of("tenantAdmin")))); mockMvc - .perform(delete("/accounts/42").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .perform( + delete("/accounts/" + ACCOUNT_UUID) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isForbidden()) .andExpect(jsonPath("$.error.code").value("PERMISSION_DENIED")) .andExpect(jsonPath("$.error.message").value("Account access required")); @@ -137,14 +144,31 @@ void exportAccountAllowsCurrentAccountWithoutTenantScope() throws Exception { AccountDto account = new AccountDto(42L, "demo", "demo@example.com", "player", true); when(accountService.exportAccountData(42L)) .thenReturn(new AccountDataExportDto(account, List.of())); - String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); + when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))).thenReturn(42L); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc - .perform(get("/accounts/42/export").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .perform( + get("/accounts/" + ACCOUNT_UUID + "/export") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")); } + @Test + void exportAccountRejectsNumericOrDifferentSubjectBeforeIdentityLookup() throws Exception { + for (String subject : List.of("42", OTHER_ACCOUNT_UUID)) { + String token = jwtUtil.generateToken(subject, Map.of("accountId", subject)); + mockMvc + .perform( + get("/accounts/" + ACCOUNT_UUID + "/export") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isForbidden()); + } + + verifyNoInteractions(accountService); + } + @Test void exportTenantDataFailsClosedWithoutReadingAccountService() throws Exception { String token = @@ -152,7 +176,7 @@ void exportTenantDataFailsClosedWithoutReadingAccountService() throws Exception mockMvc .perform( - get("/accounts/42/tenant-export") + get("/accounts/" + ACCOUNT_UUID + "/tenant-export") .param("tenantId", "7") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isNotImplemented()); @@ -166,11 +190,10 @@ void exportAccountRejectsMalformedAccountIdBeforeDispatch() throws Exception { mockMvc .perform( - get("/accounts/not-a-number/export") - .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + get("/accounts/not-a-uuid/export").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("accountId must be numeric")); + .andExpect(jsonPath("$.error.message").value("accountId must be a canonical non-nil UUID")); verifyNoInteractions(accountService); } @@ -181,7 +204,7 @@ void exportTenantDataRejectsZeroTenantIdBeforeDispatch() throws Exception { mockMvc .perform( - get("/accounts/42/tenant-export") + get("/accounts/" + ACCOUNT_UUID + "/tenant-export") .param("tenantId", "0") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) @@ -193,11 +216,11 @@ void exportTenantDataRejectsZeroTenantIdBeforeDispatch() throws Exception { @Test void deleteAccountDeniesCurrentAccountBeforeServiceMutation() throws Exception { - String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - delete("/accounts/42") + delete("/accounts/" + ACCOUNT_UUID) .param("tenantId", "7") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isConflict()) @@ -214,18 +237,18 @@ void deleteAccountRejectsZeroAccountIdBeforeDispatch() throws Exception { .perform(delete("/accounts/0").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("accountId must be positive")); + .andExpect(jsonPath("$.error.message").value("accountId must be a canonical non-nil UUID")); verifyNoInteractions(accountService); } @Test void linkExternalRouteIsUnavailableForAuthenticatedRequest() throws Exception { - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - post("/accounts/2/external") + post("/accounts/" + ACCOUNT_UUID + "/external") .contentType(MediaType.APPLICATION_JSON) .content( "{\"tenantId\":1,\"accountId\":2,\"provider\":\"steam\",\"externalId\":\"demo\"}") @@ -239,19 +262,20 @@ void linkExternalRouteIsUnavailableForAuthenticatedRequest() throws Exception { void loginAuthModesAllowCurrentAccountWithoutTenantScope() throws Exception { AccountLoginAuthModesDto modes = new AccountLoginAuthModesDto(java.util.Set.of(AccountLoginAuthMode.EMAIL_OTP)); + when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))).thenReturn(42L); when(accountService.getLoginAuthModes(42L)).thenReturn(modes); - String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - get("/accounts/42/login-auth-modes") + get("/accounts/" + ACCOUNT_UUID + "/login-auth-modes") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.data.loginAuthModes[0]").value("EMAIL_OTP")); mockMvc .perform( - put("/accounts/42/login-auth-modes") + put("/accounts/" + ACCOUNT_UUID + "/login-auth-modes") .contentType(MediaType.APPLICATION_JSON) .content("{\"loginAuthModes\":[\"EMAIL_OTP\"]}") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -276,7 +300,7 @@ void updateLoginAuthModesRejectsPlatformAdminBeforeDispatch() throws Exception { mockMvc .perform( - put("/accounts/42/login-auth-modes") + put("/accounts/" + ACCOUNT_UUID + "/login-auth-modes") .contentType(MediaType.APPLICATION_JSON) .content("{\"loginAuthModes\":[\"PASSWORD\"]}") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -288,11 +312,11 @@ void updateLoginAuthModesRejectsPlatformAdminBeforeDispatch() throws Exception { @Test void updateLoginAuthModesRejectsEmptySetBeforeDispatch() throws Exception { - String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - put("/accounts/42/login-auth-modes") + put("/accounts/" + ACCOUNT_UUID + "/login-auth-modes") .contentType(MediaType.APPLICATION_JSON) .content("{\"loginAuthModes\":[]}") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountRequestReadersTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountRequestReadersTest.java new file mode 100644 index 0000000000..5f73a4e003 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountRequestReadersTest.java @@ -0,0 +1,36 @@ +package net.firedevops.firemud.accountservice.controller; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class AccountRequestReadersTest { + private static final String ACCOUNT_UUID = "550e8400-e29b-41d4-a716-446655440000"; + + @Test + void readsCanonicalNonNilAccountUuid() { + assertEquals( + UUID.fromString(ACCOUNT_UUID), AccountRequestReaders.requireAccountUuid(ACCOUNT_UUID)); + } + + @ParameterizedTest + @ValueSource( + strings = { + "42", + "0", + "00000000-0000-0000-0000-000000000000", + "550E8400-E29B-41D4-A716-446655440000", + "not-a-uuid" + }) + void rejectsAccountIdsThatAreNotCanonicalNonNilUuids(String value) { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, () -> AccountRequestReaders.requireAccountUuid(value)); + + assertEquals("accountId must be a canonical non-nil UUID", exception.getMessage()); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java index 078f3c2c7c..483a7af433 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java @@ -41,6 +41,7 @@ @WebMvcTest(AuthController.class) @Import({CommonSecurityAutoConfiguration.class, CommonSecurityServletAutoConfiguration.class}) class AuthControllerTest { + private static final String ACCOUNT_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72001"; @Autowired private MockMvc mockMvc; private final ObjectMapper objectMapper = new ObjectMapper(); @@ -51,7 +52,7 @@ class AuthControllerTest { void loginReturnsTokenAndAccountId() throws Exception { LoginRequest request = new LoginRequest("demo", "password"); when(accountService.authenticate("demo", "password")) - .thenReturn(new AuthenticationResult(1L, "tok123")); + .thenReturn(new AuthenticationResult(ACCOUNT_UUID, "tok123")); mockMvc .perform( @@ -60,7 +61,7 @@ void loginReturnsTokenAndAccountId() throws Exception { .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.accountId").value(1)) + .andExpect(jsonPath("$.data.accountId").value(ACCOUNT_UUID)) .andExpect(jsonPath("$.data.authToken").value("tok123")); } @@ -68,7 +69,7 @@ void loginReturnsTokenAndAccountId() throws Exception { void loginAcceptsExistingOneCharacterPassword() throws Exception { LoginRequest request = new LoginRequest("demo", "x"); when(accountService.authenticate("demo", "x")) - .thenReturn(new AuthenticationResult(1L, "tok123")); + .thenReturn(new AuthenticationResult(ACCOUNT_UUID, "tok123")); mockMvc .perform( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java index 14b86c1fff..a8b74c6efa 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.accountservice.controller; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -9,6 +10,7 @@ import java.util.List; import java.util.Map; +import java.util.UUID; import net.firedevops.firemud.accountservice.dto.ProfileDto; import net.firedevops.firemud.accountservice.dto.UpdateProfileRequest; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; @@ -33,6 +35,8 @@ @Import({CommonSecurityAutoConfiguration.class, CommonSecurityServletAutoConfiguration.class}) @WithFiremudHttpAuthTestProperties class ProfileControllerTest { + private static final String ACCOUNT_UUID = "550e8400-e29b-41d4-a716-446655440000"; + private static final String OTHER_ACCOUNT_UUID = "550e8400-e29b-41d4-a716-446655440001"; @Autowired private MockMvc mockMvc; private final ObjectMapper objectMapper = new ObjectMapper(); @@ -49,12 +53,13 @@ void clear() { void getProfileReturnsDto() throws Exception { ProfileDto dto = new ProfileDto(1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); + when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))).thenReturn(2L); when(accountService.getProfile(1L, 2L)).thenReturn(dto); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - get("/profiles/2") + get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) @@ -68,12 +73,13 @@ void updateProfileReturnsDto() throws Exception { new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); ProfileDto dto = new ProfileDto(1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))).thenReturn(2L); when(accountService.updateProfile(req)).thenReturn(dto); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(req)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -89,7 +95,7 @@ void getProfileRejectsCrossTenantScopedAdmin() throws Exception { jwtUtil.generateToken("user", Map.of("scopedRoles", Map.of("8", List.of("tenantAdmin")))); mockMvc .perform( - get("/profiles/2") + get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isForbidden()); @@ -98,11 +104,12 @@ void getProfileRejectsCrossTenantScopedAdmin() throws Exception { @Test void getProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { String token = - jwtUtil.generateToken("3", Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); mockMvc .perform( - get("/profiles/2") + get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isForbidden()); @@ -112,11 +119,12 @@ void getProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { @Test void getProfileRejectsGlobalAdminForAnotherAccount() throws Exception { - String token = jwtUtil.generateToken("3", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( - get("/profiles/2") + get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isForbidden()); @@ -124,29 +132,61 @@ void getProfileRejectsGlobalAdminForAnotherAccount() throws Exception { verifyNoInteractions(accountService); } + @Test + void getProfileRejectsNumericSubjectBeforeIdentityLookup() throws Exception { + String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + + mockMvc + .perform( + get("/profiles/" + ACCOUNT_UUID) + .param("tenantId", "1") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isForbidden()); + + verifyNoInteractions(accountService); + } + + @Test + void getProfileRejectsUnmappedUuidBeforeProfileRead() throws Exception { + when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenThrow(new IllegalArgumentException("Account not found")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); + + mockMvc + .perform( + get("/profiles/" + ACCOUNT_UUID) + .param("tenantId", "1") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isBadRequest()); + + org.mockito.Mockito.verify(accountService, never()).getProfile(1L, 2L); + } + @Test void getProfileRejectsMalformedAccountIdBeforeDispatch() throws Exception { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( - get("/profiles/not-a-number") + get("/profiles/not-a-uuid") .param("tenantId", "1") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("accountId must be numeric")); + .andExpect(jsonPath("$.error.message").value("accountId must be a canonical non-nil UUID")); verifyNoInteractions(accountService); } @Test void getProfileRejectsZeroTenantIdBeforeDispatch() throws Exception { - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( - get("/profiles/2") + get("/profiles/" + ACCOUNT_UUID) .param("tenantId", "0") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) @@ -162,12 +202,13 @@ void updateProfileAllowsCurrentAccountWithoutPrivilegedTenantRole() throws Excep new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); ProfileDto dto = new ProfileDto(1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))).thenReturn(2L); when(accountService.updateProfile(req)).thenReturn(dto); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(req)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -180,11 +221,11 @@ void updateProfileRejectsReservedHiddenStaffPolicyBeforeDispatch() throws Except UpdateProfileRequest request = new UpdateProfileRequest( 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -202,11 +243,12 @@ void updateProfileRejectsUnauthorizedCallerBeforeReservedPolicyValidation() thro UpdateProfileRequest request = new UpdateProfileRequest( 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.HIDDEN_STAFF); - String token = jwtUtil.generateToken("3", Map.of("accountId", "3")); + String token = + jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("accountId", OTHER_ACCOUNT_UUID)); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -220,11 +262,12 @@ void updateProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { UpdateProfileRequest request = new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); String token = - jwtUtil.generateToken("3", Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); + jwtUtil.generateToken( + OTHER_ACCOUNT_UUID, Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -237,11 +280,12 @@ void updateProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { void updateProfileRejectsGlobalAdminForAnotherAccount() throws Exception { UpdateProfileRequest request = new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); - String token = jwtUtil.generateToken("3", Map.of("globalRoles", List.of("platformAdmin"))); + String token = + jwtUtil.generateToken(OTHER_ACCOUNT_UUID, Map.of("globalRoles", List.of("platformAdmin"))); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) @@ -264,7 +308,7 @@ void updateProfileRejectsZeroAccountIdBeforeDispatch() throws Exception { .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("accountId must be positive")); + .andExpect(jsonPath("$.error.message").value("accountId must be a canonical non-nil UUID")); verifyNoInteractions(accountService); } @@ -273,11 +317,11 @@ void updateProfileRejectsZeroAccountIdBeforeDispatch() throws Exception { void updateProfileRejectsZeroTenantIdBeforeDispatch() throws Exception { UpdateProfileRequest req = new UpdateProfileRequest(0L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); - String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + String token = jwtUtil.generateToken(ACCOUNT_UUID, Map.of("accountId", ACCOUNT_UUID)); mockMvc .perform( - put("/profiles/2") + put("/profiles/" + ACCOUNT_UUID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(req)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AuthenticationResultTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AuthenticationResultTest.java new file mode 100644 index 0000000000..747ee717c1 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AuthenticationResultTest.java @@ -0,0 +1,32 @@ +package net.firedevops.firemud.accountservice.dto; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class AuthenticationResultTest { + private static final String ACCOUNT_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72001"; + + @Test + void acceptsCanonicalNonNilAccountUuid() { + AuthenticationResult result = new AuthenticationResult(ACCOUNT_UUID, "jwt"); + + assertEquals(ACCOUNT_UUID, result.accountId()); + } + + @Test + void rejectsMissingMalformedNoncanonicalAndNilAccountUuid() { + assertThrows(IllegalArgumentException.class, () -> new AuthenticationResult(null, "jwt")); + assertThrows(IllegalArgumentException.class, () -> new AuthenticationResult("", "jwt")); + assertThrows( + IllegalArgumentException.class, + () -> new AuthenticationResult("04ef66b4-c0ad-3d5b-b3b2-0e8510e7201", "jwt")); + assertThrows( + IllegalArgumentException.class, + () -> new AuthenticationResult("04EF66B4-C0AD-3D5B-B3B2-0E8510E72001", "jwt")); + assertThrows( + IllegalArgumentException.class, + () -> new AuthenticationResult("00000000-0000-0000-0000-000000000000", "jwt")); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 0f20c736d6..e5120fab7f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -562,7 +562,9 @@ void authenticateReturnsAuthenticatedSessionForExactGameSessionPeer() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.authenticateForGameplay("demo@example.com", "password")) - .thenReturn(new net.firedevops.firemud.accountservice.dto.AuthenticationResult(9L, "jwt")); + .thenReturn( + new net.firedevops.firemud.accountservice.dto.AuthenticationResult( + ACCOUNT_UUID, "jwt")); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); @@ -577,7 +579,7 @@ void authenticateReturnsAuthenticatedSessionForExactGameSessionPeer() { .build(), observer)); - assertEquals("9", observer.response().getAccountId()); + assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); assertEquals("jwt", observer.response().getAuthToken()); assertTrue(observer.completed()); Mockito.verify(accountService).authenticateForGameplay("demo@example.com", "password"); @@ -619,7 +621,9 @@ void verifyEmailLoginOtpReturnsAuthenticatedSession() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.verifyEmailLoginOtp("demo@example.com", "123456")) - .thenReturn(new net.firedevops.firemud.accountservice.dto.AuthenticationResult(9L, "jwt")); + .thenReturn( + new net.firedevops.firemud.accountservice.dto.AuthenticationResult( + ACCOUNT_UUID, "jwt")); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); @@ -646,7 +650,7 @@ public void onCompleted() {} })); assertNotNull(ref.get()); - assertEquals("9", ref.get().getAccountId()); + assertEquals(ACCOUNT_UUID, ref.get().getAccountId()); assertEquals("jwt", ref.get().getAuthToken()); } @@ -831,6 +835,8 @@ public void onCompleted() {} void getProfileReturnsProfile() throws Exception { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); Mockito.when(accountService.getProfile(1L, 2L)) .thenReturn( new net.firedevops.firemud.accountservice.dto.ProfileDto( @@ -839,12 +845,12 @@ void getProfileReturnsProfile() throws Exception { new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - SessionContext.setContext("2", List.of("player"), Map.of()); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); withPeer( SOCIAL_GROUPS_PEER, () -> service.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("2").build(), + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), new StreamObserver() { @Override public void onNext(GetProfileResponse value) { @@ -872,6 +878,30 @@ public void onCompleted() {} .readTree(ref.get().getProfileJson()) .path("presenceVisibilityPolicy") .asText()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + } + + @Test + void getProfileRejectsUnmappedUuidBeforeProfileRead() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenThrow(new IllegalArgumentException("Account not found")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); + + withPeer( + SOCIAL_GROUPS_PEER, + () -> + service.getProfile( + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), + observer)); + + assertEquals("NOT_FOUND", observer.response().getError().getCode()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService, Mockito.never()).getProfile(1L, 2L); } @Test @@ -903,7 +933,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertEquals("accountId must be a canonical non-nil UUID", ref.get().getError().getMessage()); Mockito.verifyNoInteractions(accountService); } @@ -924,13 +954,16 @@ void getProfileRejectsMissingOrWrongPeerBeforeLookup() { AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - SessionContext.setContext("2", List.of("player"), Map.of()); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); withPeer( peer, () -> service.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("2").build(), + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .build(), observer)); assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); @@ -948,13 +981,21 @@ void getProfileRejectsInternalOrCrossAccountSubjectBeforeLookup() { new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); SessionContext.setContext( - internalService ? "2" : "3", List.of(), Map.of(), internalService, "", ""); + internalService ? ACCOUNT_UUID : OTHER_ACCOUNT_UUID, + List.of(), + Map.of(), + internalService, + "", + ""); withPeer( SOCIAL_GROUPS_PEER, () -> service.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("2").build(), + GetProfileRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_UUID) + .build(), observer)); assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); @@ -975,7 +1016,7 @@ void getProfileRejectsMissingCallerAccountSubjectBeforeLookup() { SOCIAL_GROUPS_PEER, () -> service.getProfile( - GetProfileRequest.newBuilder().setTenantId("1").setAccountId("2").build(), + GetProfileRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), observer)); assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); @@ -1377,18 +1418,20 @@ void getTenantEntitlementsForRuntimeFailsClosedForCrossTenantTarget() { void updateProfileAllowsExactSocialPeerWithMatchingSubject() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - SessionContext.setContext("2", List.of("player"), Map.of()); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); withPeer( SOCIAL_GROUPS_PEER, () -> service.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(ACCOUNT_UUID) .setProfileJson( "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") .build(), @@ -1401,6 +1444,7 @@ void updateProfileAllowsExactSocialPeerWithMatchingSubject() { org.mockito.ArgumentCaptor.forClass( net.firedevops.firemud.accountservice.dto.UpdateProfileRequest.class); Mockito.verify(accountService).updateProfile(captor.capture()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); assertEquals(1L, captor.getValue().tenantId()); assertEquals(2L, captor.getValue().accountId()); assertEquals("demo", captor.getValue().displayName()); @@ -1416,7 +1460,9 @@ void updateProfileMapsServiceRuntimeFailuresToApplicationErrors() { AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - SessionContext.setContext("2", List.of("player"), Map.of()); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); withPeer( SOCIAL_GROUPS_PEER, @@ -1424,7 +1470,7 @@ void updateProfileMapsServiceRuntimeFailuresToApplicationErrors() { service.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(ACCOUNT_UUID) .setProfileJson( "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") .build(), @@ -1452,7 +1498,7 @@ void updateProfileRejectsMissingOrWrongPeerBeforeUpdate() { AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - SessionContext.setContext("2", List.of("player"), Map.of()); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); withPeer( peer, @@ -1460,7 +1506,7 @@ void updateProfileRejectsMissingOrWrongPeerBeforeUpdate() { service.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(ACCOUNT_UUID) .setProfileJson( "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") .build(), @@ -1481,7 +1527,12 @@ void updateProfileRejectsCrossAccountOrInternalSubjectBeforeUpdate() { new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); SessionContext.setContext( - internalService ? "2" : "3", List.of(), Map.of(), internalService, "", ""); + internalService ? ACCOUNT_UUID : OTHER_ACCOUNT_UUID, + List.of(), + Map.of(), + internalService, + "", + ""); withPeer( SOCIAL_GROUPS_PEER, @@ -1489,7 +1540,7 @@ void updateProfileRejectsCrossAccountOrInternalSubjectBeforeUpdate() { service.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(ACCOUNT_UUID) .setProfileJson( "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") .build(), @@ -1516,7 +1567,7 @@ void updateProfileRejectsMissingCallerAccountSubjectBeforeUpdate() { service.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId(ACCOUNT_UUID) .setProfileJson( "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") .build(), @@ -1535,14 +1586,14 @@ void updateProfileRejectsZeroTenantIdBeforeUpdate() { new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - SessionContext.setContext("2", List.of("player"), Map.of()); + SessionContext.setContext(ACCOUNT_UUID, List.of("player"), Map.of()); withPeer( SOCIAL_GROUPS_PEER, () -> service.updateProfile( UpdateProfileRequest.newBuilder() .setTenantId("0") - .setAccountId("2") + .setAccountId(ACCOUNT_UUID) .setProfileJson( "{\"displayName\":\"demo\",\"bio\":\"bio\",\"presenceVisibilityPolicy\":\"PRIVATE\"}") .build(), diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 0d11463c9a..2af7e66166 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -1581,6 +1581,7 @@ void emailLoginOtpRequestPersistsOnlyHashedChallengeAndSendsSixDigitCode() { void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { Account account = new Account(); account.setId(9L); + setPersistedAuthenticationIdentity(account); account.setEmail("verified@example.com"); account.setEmailVerified(true); account.setRole("player"); @@ -1613,7 +1614,7 @@ void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { AuthenticationResult result = service.verifyEmailLoginOtp("verified@example.com", codeMatcher.group(1)); - assertEquals(9L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); assertNotNull(result.authToken()); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) .delete(challengeCaptor.getValue()); @@ -1629,6 +1630,7 @@ void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { Account account = new Account(); account.setId(9L); + setPersistedAuthenticationIdentity(account); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = @@ -1643,7 +1645,7 @@ void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "123456"); - assertEquals(9L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).delete(challenge); org.mockito.Mockito.verify(sessionService) .storeAccountSession(9L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); @@ -1654,6 +1656,7 @@ void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { void authenticateFallsBackToPasswordWithoutBurningUnmatchedEmailLoginOtp() { Account account = new Account(); account.setId(9L); + setPersistedAuthenticationIdentity(account); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = @@ -1668,7 +1671,7 @@ void authenticateFallsBackToPasswordWithoutBurningUnmatchedEmailLoginOtp() { AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - assertEquals(9L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) .delete(challenge); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) @@ -1735,6 +1738,7 @@ void emailLoginOtpVerificationFailsClosedForUnknownEmail() { void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { Account account = new Account(); account.setId(9L); + setPersistedAuthenticationIdentity(account); account.setEmail("verified@example.com"); account.setRole("player"); net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = @@ -1750,10 +1754,11 @@ void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { AuthenticationResult result = service.verifyEmailLoginOtp("verified@example.com", "123456"); - assertEquals(9L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); assertEquals("account-service", claims.getAudience().iterator().next()); - assertEquals(9L, claims.get("accountId", Long.class)); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(9L); inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(9L); @@ -1764,6 +1769,7 @@ void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { void authenticateReturnsControlUiTokenWithoutGameplayMembership() { Account account = new Account(); account.setId(1L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1771,10 +1777,11 @@ void authenticateReturnsControlUiTokenWithoutGameplayMembership() { AuthenticationResult result = service.authenticate("demo", "password"); assertNotNull(result.authToken()); - assertEquals(1L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); assertEquals("control-ui", claims.getAudience().iterator().next()); - assertEquals(1L, claims.get("accountId", Long.class)); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); assertEquals(java.util.List.of(), claims.get("globalRoles")); assertNotNull(claims.get("jti")); assertFalse(claims.containsKey("tenantId")); @@ -1809,6 +1816,7 @@ void authenticateRejectsIneligibleLifecycleState( void authenticateForGameplayReturnsTokenWhenPasswordMatches() { Account account = new Account(); account.setId(1L); + setPersistedAuthenticationIdentity(account); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); @@ -1817,10 +1825,11 @@ void authenticateForGameplayReturnsTokenWhenPasswordMatches() { AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); assertNotNull(result.authToken()); - assertEquals(1L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); assertEquals("account-service", claims.getAudience().iterator().next()); - assertEquals(1L, claims.get("accountId", Long.class)); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); assertEquals(java.util.List.of(), claims.get("globalRoles")); assertNotNull(claims.get("jti")); org.mockito.Mockito.verify(sessionService) @@ -1828,10 +1837,131 @@ void authenticateForGameplayReturnsTokenWhenPasswordMatches() { verifyNoInteractions(accountTenantMembershipRepository); } + @ParameterizedTest + @EnumSource(AccountIdentityProvenance.class) + void resolveAccountStorageIdAcceptsEveryExactPersistedUuidProvenance( + AccountIdentityProvenance provenance) { + UUID accountUuid = UUID.randomUUID(); + Account account = new Account(); + account.setId(31L); + account.setAccountUuid(accountUuid); + account.setAccountUuidProvenance(provenance); + account.setAccountUuidSourceNumericId(31L); + when(accountRepository.findByAccountUuid(accountUuid)).thenReturn(Optional.of(account)); + + assertEquals(31L, service.resolveAccountStorageId(accountUuid)); + + verify(accountRepository).findByAccountUuid(accountUuid); + verifyNoInteractions(profileRepository); + } + + @ParameterizedTest + @EnumSource(InvalidAuthenticationIdentity.class) + void resolveAccountStorageIdRejectsUnprovedUuidBeforeProfileOperations( + InvalidAuthenticationIdentity invalidIdentity) { + UUID accountUuid = UUID.randomUUID(); + Account account = new Account(); + account.setId(32L); + setPersistedAuthenticationIdentity(account); + assignInvalidAuthenticationIdentity(account, invalidIdentity); + when(accountRepository.findByAccountUuid(accountUuid)).thenReturn(Optional.of(account)); + + assertThrows(IllegalStateException.class, () -> service.resolveAccountStorageId(accountUuid)); + + verify(accountRepository).findByAccountUuid(accountUuid); + verifyNoInteractions(profileRepository); + } + + @Test + void resolveAccountStorageIdRejectsMissingOrNilUuidBeforeLookup() { + assertThrows(IllegalArgumentException.class, () -> service.resolveAccountStorageId(null)); + assertThrows( + IllegalArgumentException.class, () -> service.resolveAccountStorageId(new UUID(0L, 0L))); + + verifyNoInteractions(accountRepository, profileRepository); + } + + @Test + void resolveAccountStorageIdRejectsMissingAccountBeforeProfileOperations() { + UUID accountUuid = UUID.randomUUID(); + when(accountRepository.findByAccountUuid(accountUuid)).thenReturn(Optional.empty()); + + assertThrows( + IllegalArgumentException.class, () -> service.resolveAccountStorageId(accountUuid)); + + verify(accountRepository).findByAccountUuid(accountUuid); + verifyNoInteractions(profileRepository); + } + + @Test + void resolveAccountStorageIdRejectsReadbackForAnotherUuid() { + UUID requestedUuid = UUID.randomUUID(); + Account account = new Account(); + account.setId(33L); + setPersistedAuthenticationIdentity(account); + when(accountRepository.findByAccountUuid(requestedUuid)).thenReturn(Optional.of(account)); + + assertThrows(IllegalStateException.class, () -> service.resolveAccountStorageId(requestedUuid)); + + verifyNoInteractions(profileRepository); + } + + @ParameterizedTest + @EnumSource(AccountIdentityProvenance.class) + void authenticateAcceptsEveryExactPersistedUuidProvenance(AccountIdentityProvenance provenance) { + Account account = new Account(); + account.setId(31L); + account.setEmail("retained@example.com"); + account.setPasswordHash(hash("password")); + setPersistedAuthenticationIdentity(account, provenance); + when(accountRepository.findByEmail("retained@example.com")).thenReturn(Optional.of(account)); + + AuthenticationResult result = + service.authenticateForGameplay("retained@example.com", "password"); + + assertEquals(account.getAccountUuid().toString(), result.accountId()); + var claims = parseClaims(result.authToken()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId", String.class)); + assertFalse(claims.containsKey("tenantId")); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(31L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + } + + @ParameterizedTest + @EnumSource(InvalidAuthenticationIdentity.class) + void authenticationRejectsUnprovedIdentityBeforeConsumingChallengeOrStoringSession( + InvalidAuthenticationIdentity invalidIdentity) { + Account account = new Account(); + account.setId(32L); + account.setEmail("unproved@example.com"); + assignInvalidAuthenticationIdentity(account, invalidIdentity); + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(8L); + challenge.setAccountId(32L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByEmail("unproved@example.com")).thenReturn(Optional.of(account)); + when(accountEmailLoginChallengeRepository.findByAccountId(32L)) + .thenReturn(Optional.of(challenge)); + + assertThrows( + IllegalStateException.class, + () -> service.authenticateForGameplay("unproved@example.com", "123456")); + + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(32L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).findByAccountId(32L); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(challenge); + verifyNoInteractions(sessionService); + } + @Test void accountJwtMintPathsRemainCanonicalAndConnectTokenFailsClosedWithoutAuthorityTuple() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); @@ -1841,9 +1971,13 @@ void accountJwtMintPathsRemainCanonicalAndConnectTokenFailsClosedWithoutAuthorit AuthenticationResult controlUi = service.authenticate("demo", "password"); AuthenticationResult gameplayDelegation = service.authenticateForGameplay("demo@example.com", "password"); - assertCanonicalIssuerAndClaims(controlUi.authToken(), "control-ui", 11L); + assertEquals(account.getAccountUuid().toString(), controlUi.accountId()); + assertEquals(account.getAccountUuid().toString(), gameplayDelegation.accountId()); + assertCanonicalIssuerAndClaims( + controlUi.authToken(), "control-ui", account.getAccountUuid().toString()); assertEquals(java.util.List.of(), parseClaims(controlUi.authToken()).get("globalRoles")); - assertCanonicalIssuerAndClaims(gameplayDelegation.authToken(), "account-service", 11L); + assertCanonicalIssuerAndClaims( + gameplayDelegation.authToken(), "account-service", account.getAccountUuid().toString()); assertEquals( java.util.List.of(), parseClaims(gameplayDelegation.authToken()).get("globalRoles")); @@ -1878,6 +2012,7 @@ void accountJwtMintPathsRemainCanonicalAndConnectTokenFailsClosedWithoutAuthorit Account otpAccount = new Account(); otpAccount.setId(12L); + setPersistedAuthenticationIdentity(otpAccount); otpAccount.setEmail("otp@example.com"); otpAccount.setLoginAuthModes("EMAIL_OTP"); var challenge = new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); @@ -1888,7 +2023,9 @@ void accountJwtMintPathsRemainCanonicalAndConnectTokenFailsClosedWithoutAuthorit when(accountEmailLoginChallengeRepository.findByAccountId(12L)) .thenReturn(Optional.of(challenge)); AuthenticationResult otpDelegation = service.verifyEmailLoginOtp("otp@example.com", "123456"); - assertCanonicalIssuerAndClaims(otpDelegation.authToken(), "account-service", 12L); + assertEquals(otpAccount.getAccountUuid().toString(), otpDelegation.accountId()); + assertCanonicalIssuerAndClaims( + otpDelegation.authToken(), "account-service", otpAccount.getAccountUuid().toString()); assertEquals(java.util.List.of(), parseClaims(otpDelegation.authToken()).get("globalRoles")); } @@ -2529,6 +2666,7 @@ void issueConnectTokenRejectsZeroPointerVersionInConnectScopeClaims() { void authenticateForGameplayUsesNormalizedEmailLookup() { Account account = new Account(); account.setId(1L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); @@ -2538,7 +2676,7 @@ void authenticateForGameplayUsesNormalizedEmailLookup() { service.authenticateForGameplay(" DEMO@example.com ", "password"); assertNotNull(result.authToken()); - assertEquals(1L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); org.mockito.Mockito.verify(sessionService) .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); verifyNoInteractions(accountTenantMembershipRepository); @@ -2573,12 +2711,13 @@ void authenticateDoesNotUseGlobalAccountFallback() { void authenticateAllowsGlobalIdentityWithoutTenantMembership() { Account account = new Account(); account.setId(7L); + setPersistedAuthenticationIdentity(account); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - assertEquals(7L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); assertNotNull(result.authToken()); org.mockito.Mockito.verify(sessionService) .storeAccountSession(7L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); @@ -5225,6 +5364,49 @@ private void assertCanonicalIssuerAndClaims( assertNotNull(claims.get("jti")); } + private void assertCanonicalIssuerAndClaims( + String token, String expectedAudience, String expectedAccountUuid) { + var claims = parseClaims(token); + assertEquals("firemud-account-service", claims.getIssuer()); + assertEquals(expectedAudience, claims.getAudience().iterator().next()); + assertEquals(expectedAccountUuid, claims.getSubject()); + assertEquals(expectedAccountUuid, claims.get("accountId", String.class)); + assertNotNull(claims.get("jti")); + assertFalse(claims.containsKey("tenantId")); + } + + private static void setPersistedAuthenticationIdentity(Account account) { + setPersistedAuthenticationIdentity( + account, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + } + + private static void setPersistedAuthenticationIdentity( + Account account, AccountIdentityProvenance provenance) { + account.setAccountUuid(UUID.randomUUID()); + account.setAccountUuidProvenance(provenance); + account.setAccountUuidSourceNumericId(account.getId()); + } + + private static void assignInvalidAuthenticationIdentity( + Account account, InvalidAuthenticationIdentity failure) { + setPersistedAuthenticationIdentity(account); + switch (failure) { + case MISSING_UUID -> account.setAccountUuid(null); + case NIL_UUID -> account.setAccountUuid(new UUID(0L, 0L)); + case MISSING_PROVENANCE -> account.setAccountUuidProvenance(null); + case MISSING_SOURCE_ROW -> account.setAccountUuidSourceNumericId(null); + case CONTRADICTORY_SOURCE_ROW -> account.setAccountUuidSourceNumericId(33L); + } + } + + private enum InvalidAuthenticationIdentity { + MISSING_UUID, + NIL_UUID, + MISSING_PROVENANCE, + MISSING_SOURCE_ROW, + CONTRADICTORY_SOURCE_ROW + } + private io.jsonwebtoken.Claims parseClaims(String token) { return new JwtUtil(JWT_SECRET, 3600000L).parseToken(token).getPayload(); } 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..7dc80a2e4b 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 @@ -355,6 +355,7 @@ public GameplayCommand save(GameplayCommand entity) { .set(GAMEPLAY_COMMAND.GAME_INSTANCE_ID, entity.getGameInstanceId()) .set(GAMEPLAY_COMMAND.SESSION_ID, entity.getSessionId()) .set(GAMEPLAY_COMMAND.ACCOUNT_ID, entity.getAccountId()) + .set(GAMEPLAY_COMMAND.ACCOUNT_UUID, entity.getAccountUuid()) .set(GAMEPLAY_COMMAND.CHARACTER_ID, entity.getCharacterId()) .set(GAMEPLAY_COMMAND.COMMAND_NAME, entity.getCommandName()) .set(GAMEPLAY_COMMAND.COMMAND_TEXT, entity.getCommandText()) @@ -603,6 +604,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 +663,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/V9__gameplay_command_account_uuid.sql b/services/game-session-service/src/main/resources/db/migration/V9__gameplay_command_account_uuid.sql new file mode 100644 index 0000000000..17afc0c86f --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V9__gameplay_command_account_uuid.sql @@ -0,0 +1,9 @@ +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..03ddebf81d --- /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("8")) + .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..0d76be1111 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; @@ -455,6 +456,88 @@ void saveRoundTripsExecutionHook() { .isEqualTo("runtime.workflow.wave"); } + @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.setAttemptCount(1); + GameplayCommand updated = repository.save(saved); + + assertThat(updated) + .extracting(GameplayCommand::getAccountId, GameplayCommand::getAccountUuid) + .containsExactly(712L, accountUuid); + assertThat(updated.getAttemptCount()).isEqualTo(1); + } + + @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); + } + + @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 tenantAndGameQualifiedCommandLookupDoesNotCrossScope() { GameplayCommand command = new GameplayCommand(); From acd7693e7c727a16bc68f89c8f74c62415001463 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 03:20:07 +1300 Subject: [PATCH 08/23] Fix UUID database proof fixture and reuse membership identity guard --- .../player-access-and-session.md | 6 ++++- ...ountAuthenticationUuidIntegrationTest.java | 4 ++-- .../gamesession/client/AccountClient.java | 18 +++----------- .../gamesession/service/AccountIds.java | 22 +++++++++++++++++ .../gamesession/service/AccountIdsTest.java | 24 +++++++++++++++++++ 5 files changed, 56 insertions(+), 18 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountIds.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/AccountIdsTest.java 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 bea7d5acdc..e09a219f92 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,11 @@ This is a non-normative implementation tracker for player access and session. Ca The Account authentication producer now returns its exact persisted canonical non-nil UUID and signs that same identity in `sub`/`accountId` for password and email-OTP paths. Profile and supported self-service readers first bind the canonical UUID to the authenticated subject, then perform an Account-owned read-only provenance-checked lookup of the private numeric storage key; an unmapped UUID cannot select or mutate another row. Disabled deletion, login-factor mutation and tenant export remain denied without writes. Other numeric DTO, catalog and cross-service consumers are explicitly unfinished; this component does not establish a working end-to-end login/admission path. Game Session V9 separately adds exact command UUID storage without altering or inventing identities for retained numeric rows. The consumer-carrier correction remains a separate unpublished candidate. -Local consolidated Account/Game Session full checks and JARs passed (156 tasks, 72 executed/84 up-to-date), including formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown. Account's 502 unit cases passed in the preceding same-code execution; their final task was up-to-date, not a second execution. All 149 Account PostgreSQL cases compiled/discovered and skipped without Docker, including the three new persisted-identity/profile no-mutation cases. Game Session executed 1,747 unit, 18 non-PostgreSQL integration and one cross-service case; 17 unit, 133 integration and 33 cross-service cases skipped, including five new command-storage/migration cases. Strict CI component gates now require all eight new cases to execute, but have not yet supplied runner proof for this correction. The earlier possible-null integration fixture readback defect was corrected with explicit required-row checks, not an analyzer suppression. Ring publication infrastructure is an open Platform Operations prerequisite; its mount and all previously denied activation paths remain held back. +Local consolidated Account/Game Session full checks and JARs passed (156 tasks, 72 executed/84 up-to-date), including formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown. Account's 502 unit cases passed in the preceding same-code execution; their final task was up-to-date, not a second execution. All 149 Account PostgreSQL cases compiled/discovered and skipped without Docker, including the three new persisted-identity/profile no-mutation cases. Game Session executed 1,747 unit, 18 non-PostgreSQL integration and one cross-service case; 17 unit, 133 integration and 33 cross-service cases skipped, including five new command-storage/migration cases. The earlier possible-null integration fixture readback defect was corrected with explicit required-row checks, not an analyzer suppression. Ring publication infrastructure is an open Platform Operations prerequisite; its mount and all previously denied activation paths remain held back. + +Exact Account UUID producer/command-storage head `47153d26ca38af56033962d0fc962842ddf9b7f7` [CI36869808167](https://github.com/benhook1013/FireMUD/actions/runs/36869808167) completed FAILURE. Game Session's strict component verifier proved all five new PostgreSQL command-storage/migration cases executed once with zero skips, failures or errors. Account ran all three persisted-UUID/profile cases with zero skips: two passed, while the immutable-UUID update case expected jOOQ's exception instead of Spring's `DataIntegrityViolationException`; the database guard rejected the update as intended, but the failed assertion prevented strict Account verification. The corrected fixture retains the exact guard-message and unchanged-row assertions; corrected-head PostgreSQL execution remains required. Broader Game Session validation was cancelled after 18 Communication WebSocket failures; Python/dev-tools, Automation, Game Design and TCP jobs also failed. No aggregate or end-to-end success is claimed. + +The existing membership-client UUID guard now uses a shared Game Session `AccountIds` helper with unchanged validation semantics and two focused positive/negative tests; it does not change public signatures or enable a path. The corrected fixture and guard passed the local full Game Session check/JAR and Account integration compilation/analyzers (136 tasks, 32 executed/104 up-to-date): 1,749 unit, 18 non-PostgreSQL integration and one cross-service case executed with no failures/errors; 17 unit, 133 integration and 33 cross-service cases skipped. The Account integration analyzer correction also passed an explicit `fullCheck` gate. All local PostgreSQL skips remain skips, not runner execution. The larger carrier candidate remains unpublished and compiler-incomplete; required fixtures and owner proof will not be dropped to fit a review ceiling. Exact published receiver head `2e37b38f5fc022844f97ce654e4678771c620376` [CI36858344954](https://github.com/benhook1013/FireMUD/actions/runs/36858344954) completed FAILURE overall but passed both mandatory Game Session PostgreSQL component gates: intake5, snapshot3 and association9 all executed with zero skips/failures/errors; all seven required new snapshot/association methods executed once and passed. This proves the component source fence, exact immutable association, concurrency, lost-response retry and rollback cases that skipped locally, not a live authenticated handoff or admission. The broader Game Session check was subsequently cancelled and is not green. Evidence is the strict runner JUnit verifier output; downloaded failure artifacts are HTML, not raw JUnit XML. Game Design's dedicated association9 suite also passed. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java index 1b4ee5ef07..9336c31e34 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java @@ -30,12 +30,12 @@ import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import org.jooq.DSLContext; -import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.dao.DataIntegrityViolationException; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; @@ -153,7 +153,7 @@ void databaseInsertAuthenticationUsesTriggerProvedUuidAndCannotRemapItsSource() "UPDATE accounts SET account_uuid = ? WHERE id = ?", attemptedReplacement, accountId)) - .isInstanceOf(DataAccessException.class) + .isInstanceOf(DataIntegrityViolationException.class) .hasStackTraceContaining("Account identity cannot be reassigned"); assertThat(accountUuidFor(accountId)).isEqualTo(accountUuid); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java index 3046e16ead..fc2e5e5a3e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java @@ -4,7 +4,6 @@ import io.grpc.StatusRuntimeException; import jakarta.annotation.PostConstruct; import java.util.Objects; -import java.util.UUID; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AccountServiceGrpc; @@ -30,6 +29,7 @@ import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.slf4j.Logger; @@ -294,8 +294,8 @@ private JoinPublicProductionMembershipResponse joinError(String code, String mes public GetTenantMembershipForRuntimeResponse getTenantMembershipForRuntime( PlayerExecutionContext playerContext) { if (playerContext == null - || !isCanonicalNonNilUuid(playerContext.getAccountId()) - || !isCanonicalNonNilUuid(playerContext.getTenantId())) { + || !AccountIds.isCanonicalNonNilUuid(playerContext.getAccountId()) + || !AccountIds.isCanonicalNonNilUuid(playerContext.getTenantId())) { return membershipAuthorityUnavailable(); } if (stub() == null) { @@ -325,18 +325,6 @@ public GetTenantMembershipForRuntimeResponse getTenantMembershipForRuntime( return membershipAuthorityUnavailable(); } - private static boolean isCanonicalNonNilUuid(String value) { - if (value == null || value.isEmpty()) { - return false; - } - try { - UUID parsed = UUID.fromString(value); - return !parsed.equals(new UUID(0L, 0L)) && parsed.toString().equals(value); - } catch (IllegalArgumentException ex) { - return false; - } - } - private GetTenantMembershipForRuntimeResponse membershipAuthorityUnavailable() { return GetTenantMembershipForRuntimeResponse.newBuilder() .setError( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountIds.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountIds.java new file mode 100644 index 0000000000..a3a63d6f5a --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountIds.java @@ -0,0 +1,22 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.UUID; + +/** Validation for canonical Account logical identifiers carried by Game Session. */ +public final class AccountIds { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AccountIds() {} + + public static boolean isCanonicalNonNilUuid(String value) { + if (value == null || value.isEmpty()) { + return false; + } + try { + UUID parsed = UUID.fromString(value); + return !NIL_UUID.equals(parsed) && parsed.toString().equals(value); + } catch (IllegalArgumentException ex) { + return false; + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/AccountIdsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/AccountIdsTest.java new file mode 100644 index 0000000000..202ff736cc --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/AccountIdsTest.java @@ -0,0 +1,24 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +class AccountIdsTest { + + @Test + void acceptsCanonicalNonNilUuid() { + assertTrue(AccountIds.isCanonicalNonNilUuid("123e4567-e89b-12d3-a456-426614174000")); + } + + @Test + void rejectsNullEmptyNumericNilUppercaseAndShortFormValues() { + assertFalse(AccountIds.isCanonicalNonNilUuid(null)); + assertFalse(AccountIds.isCanonicalNonNilUuid("")); + assertFalse(AccountIds.isCanonicalNonNilUuid("12345")); + assertFalse(AccountIds.isCanonicalNonNilUuid("00000000-0000-0000-0000-000000000000")); + assertFalse(AccountIds.isCanonicalNonNilUuid("123E4567-E89B-12D3-A456-426614174000")); + assertFalse(AccountIds.isCanonicalNonNilUuid("1-1-1-1-1")); + } +} From 6e5fc2321b582ef5e74962968fa1b069b87b263e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 04:13:18 +1300 Subject: [PATCH 09/23] fix(account): retain rejected OTP attempts and prove UUID routes --- .github/workflows/ci.yml | 11 ++ design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 6 +- .../service/impl/AccountServiceImpl.java | 9 +- .../AccountApplicationIntegrationTest.java | 8 +- ...ountAuthenticationUuidIntegrationTest.java | 187 +++++++++++++++++- .../service/impl/AccountServiceImplTest.java | 56 ++++++ 7 files changed, 273 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8b88000c37..438a06bf14 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -993,13 +993,24 @@ jobs: run: | ./gradlew :account-service:integrationTest \ --tests net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest \ + --tests net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest.exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope \ + --tests net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest.updateProfileRejectsZeroTenantIdWithInvalidArgumentEnvelope \ -PfullCheck --no-build-cache --no-configuration-cache bash dev-tools/validation/inspect-test-results.sh \ --strict \ --require-suite net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest \ + --require-suite net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest \ --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#repositoryInsertAuthenticationUsesExactPersistedUuidAndPrivateStorageKey()' \ --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#databaseInsertAuthenticationUsesTriggerProvedUuidAndCannotRemapItsSource()' \ --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#unmappedUuidDeniesProfileMutationEvenWhenBodyNamesAnExistingPrivateRow()' \ + --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#emailOtpAuthenticationIssuesPersistedUuidAndConsumesTheChallengeExactlyOnce()' \ + --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#rejectedEmailOtpPersistsChallengeAttemptForControlUiAuthentication()' \ + --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#rejectedEmailOtpPersistsChallengeAttemptForGameplayAuthentication()' \ + --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#rejectedEmailOtpPersistsChallengeAttemptForOtpCompletion()' \ + --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#rejectedEmailOtpPersistsChallengeAttemptForPlayerBootstrap()' \ + --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#nonAuthenticationSessionFailureRollsBackOtpConsumption()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest#exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest#updateProfileRejectsZeroTenantIdWithInvalidArgumentEnvelope()' \ account-service - name: Run Game Session command Account UUID storage PostgreSQL component proof diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index ea0a1df76b..0ebb6065a9 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -179,3 +179,8 @@ Entry format: - Context: the Game Design owner-read test loaded `application.yml` by its generic classpath name, while several modules provide that same resource name. - Observation: the test saw an empty method allowlist rather than the owning service's configuration. Loading the module's explicit `src/main/resources` files exposed the actual default and production lists; the corrected assertion passed without weakening the required methods. This is local configuration proof, not live workload authentication. - Expected pattern: use an explicit owner-module resource when proving a service's configuration, and keep runtime classpath precedence and authenticated deployment proof separate. + +- `2026-10-02`: Use explicit typed result extraction for jOOQ SQL fixture readback + - Context: repeated Account PostgreSQL fixtures supplied `Long.class` or `UUID.class` to `DSLContext.fetchValue(String, Object...)` as if that SQL overload selected a return type. + - Observation: the class is a bind argument, not a type selector; compilation alone did not prove correct SQL binding. Integration inspection corrected the fixtures before claiming execution. + - Expected pattern: bind only actual SQL parameters with `resultQuery(sql, parameters)`, then use `fetchOne(columnIndex, type)` for typed extraction and an explicit required-row check where absence is impossible. Retain separate PostgreSQL execution proof; analyzer or compiler success is not that proof. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index e09a219f92..1f796d059c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,7 +12,11 @@ Local consolidated Account/Game Session full checks and JARs passed (156 tasks, Exact Account UUID producer/command-storage head `47153d26ca38af56033962d0fc962842ddf9b7f7` [CI36869808167](https://github.com/benhook1013/FireMUD/actions/runs/36869808167) completed FAILURE. Game Session's strict component verifier proved all five new PostgreSQL command-storage/migration cases executed once with zero skips, failures or errors. Account ran all three persisted-UUID/profile cases with zero skips: two passed, while the immutable-UUID update case expected jOOQ's exception instead of Spring's `DataIntegrityViolationException`; the database guard rejected the update as intended, but the failed assertion prevented strict Account verification. The corrected fixture retains the exact guard-message and unchanged-row assertions; corrected-head PostgreSQL execution remains required. Broader Game Session validation was cancelled after 18 Communication WebSocket failures; Python/dev-tools, Automation, Game Design and TCP jobs also failed. No aggregate or end-to-end success is claimed. -The existing membership-client UUID guard now uses a shared Game Session `AccountIds` helper with unchanged validation semantics and two focused positive/negative tests; it does not change public signatures or enable a path. The corrected fixture and guard passed the local full Game Session check/JAR and Account integration compilation/analyzers (136 tasks, 32 executed/104 up-to-date): 1,749 unit, 18 non-PostgreSQL integration and one cross-service case executed with no failures/errors; 17 unit, 133 integration and 33 cross-service cases skipped. The Account integration analyzer correction also passed an explicit `fullCheck` gate. All local PostgreSQL skips remain skips, not runner execution. The larger carrier candidate remains unpublished and compiler-incomplete; required fixtures and owner proof will not be dropped to fit a review ceiling. +The existing membership-client UUID guard now uses a shared Game Session `AccountIds` helper with unchanged validation semantics and two focused positive/negative tests; it does not change public signatures or enable a path. The corrected fixture and guard passed the local full Game Session check/JAR and Account integration compilation/analyzers (136 tasks, 32 executed/104 up-to-date): 1,749 unit, 18 non-PostgreSQL integration and one cross-service case executed with no failures/errors; 17 unit, 133 integration and 33 cross-service cases skipped. The Account integration analyzer correction also passed an explicit `fullCheck` gate. All local PostgreSQL skips remain skips, not runner execution. + +Corrected exact head `acd7693e7c727a16bc68f89c8f74c62415001463` [CI36875629815](https://github.com/benhook1013/FireMUD/actions/runs/36875629815) passed strict Account authentication3/3 and Game Session command UUID storage/migration5/5 with zero skips, failures or errors. This resolves the earlier exception-fixture failure, not wider job or runtime readiness. Aggregate CI remained FAILURE. Its two broader Account HTTP test failures were stale numeric-identity fixtures: malformed Account input expected the old numeric error, and a tenant-zero test used a numeric path/subject that failed the UUID guard first. The corrected fixtures preserve the exact status/error and tenant guard assertions. Python lint, the dev-demo summary contract, Automation formatting, TCP cross-service and Game Design EntityDigest also failed; the broader Game Session job was cancelled after component proof. The separate unpublished carrier tree now passes its full local Game Session check/JAR after exact UUID fixture corrections: 1,752 unit, 18 non-PostgreSQL integration and one cross-service case executed without failures/errors; 17 unit, 133 integration and 33 cross-service cases skipped. That local proof neither supplies PostgreSQL execution nor permits an over-ceiling publication. + +The subsequent Account batch corrects the existing email-OTP throw-after-write transaction defect: rejected attempts and exhausted/expired challenge cleanup survive `AuthenticationException` at the four authentication entrypoints, while non-authentication session-storage failure still rolls back challenge consumption. Bootstrap also proves persisted Account identity before consuming a successful challenge; its remaining numeric token/DTO carrier is still an explicit migration obligation, not a UUID-complete bootstrap claim. Six additional PostgreSQL cases exercise actual OTP delivery/challenge persistence, exact persisted UUID issuance/one-use consumption, durable wrong-code counters at all four entrypoints, and non-authentication rollback. The mandatory early CI gate now requires all nine UUID/OTP cases plus the two corrected HTTP assertions. Local full Account check/JAR, Java formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown passed (70 tasks, 18 executed/52 up-to-date), with 502 unit executions and zero skips/failures/errors. All 155 PostgreSQL cases compiled/discovered but skipped without Docker; the new nine-plus-two component requires exact-head runner execution. Historical three-case execution does not prove this batch. Activation gates remain closed. Exact published receiver head `2e37b38f5fc022844f97ce654e4678771c620376` [CI36858344954](https://github.com/benhook1013/FireMUD/actions/runs/36858344954) completed FAILURE overall but passed both mandatory Game Session PostgreSQL component gates: intake5, snapshot3 and association9 all executed with zero skips/failures/errors; all seven required new snapshot/association methods executed once and passed. This proves the component source fence, exact immutable association, concurrency, lost-response retry and rollback cases that skipped locally, not a live authenticated handoff or admission. The broader Game Session check was subsequently cancelled and is not green. Evidence is the strict runner JUnit verifier output; downloaded failure artifacts are HTML, not raw JUnit XML. Game Design's dedicated association9 suite also passed. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index f1add695d8..0f9939ad29 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -289,7 +289,7 @@ private void requireAuthenticationPersistedIdentity(Account account) { } @Override - @Transactional + @Transactional(noRollbackFor = AuthenticationException.class) @Timed(value = "account.authenticate") public net.firedevops.firemud.accountservice.dto.AuthenticationResult authenticate( String username, String password) { @@ -309,7 +309,7 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult authentica } @Override - @Transactional + @Transactional(noRollbackFor = AuthenticationException.class) @Timed(value = "account.authenticate_gameplay") public net.firedevops.firemud.accountservice.dto.AuthenticationResult authenticateForGameplay( String email, String password) { @@ -371,7 +371,7 @@ public void requestEmailLoginOtp(String email) { } @Override - @Transactional + @Transactional(noRollbackFor = AuthenticationException.class) @Timed(value = "account.verify_email_login_otp") public net.firedevops.firemud.accountservice.dto.AuthenticationResult verifyEmailLoginOtp( String email, String code) { @@ -409,12 +409,13 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult verifyEmai } @Override - @Transactional + @Transactional(noRollbackFor = AuthenticationException.class) @Timed(value = "account.player_bootstrap") public PlayerBootstrapResult issuePlayerBootstrap(String accountIdentifier, String secret) { PrimaryAuthentication authentication = authenticateAccountIdentity(accountIdentifier, secret, true); Account account = authentication.account(); + requireAuthenticationPersistedIdentity(account); authentication.emailLoginChallenge().ifPresent(accountEmailLoginChallengeRepository::delete); String jti = UUID.randomUUID().toString(); long issuedAt = System.currentTimeMillis(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index bb193c088b..691667a302 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -389,7 +389,8 @@ void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws assertThat(response.statusCode()).isEqualTo(400); assertThat(response.body()).contains("\"code\":\"INVALID_ARGUMENT\""); - assertThat(response.body()).contains("\"message\":\"accountId must be numeric\""); + assertThat(response.body()) + .contains("\"message\":\"accountId must be a canonical non-nil UUID\""); } @Test @@ -413,9 +414,10 @@ void linkExternalRouteIsUnavailableWithAuthenticatedRequest() throws Exception { @Test void updateProfileRejectsZeroTenantIdWithInvalidArgumentEnvelope() throws Exception { - String token = jwtUtil.generateToken("2", java.util.Map.of("accountId", "2")); + String accountUuid = "457336d4-63d7-4a3a-a481-ceecb1c8c296"; + String token = jwtUtil.generateToken(accountUuid, java.util.Map.of("accountId", accountUuid)); HttpRequest request = - HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/profiles/2")) + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/profiles/" + accountUuid)) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .header(HttpHeaders.CONTENT_TYPE, "application/json") .PUT( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java index 9336c31e34..4f7a02e8ae 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java @@ -11,6 +11,8 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.AccountServiceApplication; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; @@ -24,6 +26,7 @@ import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.session.SessionService; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.security.SessionContext; @@ -33,9 +36,11 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; @@ -62,6 +67,14 @@ class AccountAuthenticationUuidIntegrationTest { private static final String PASSWORD = "account-auth-test-password"; private static final long PROFILE_TENANT_ID = 98123L; + private static final Pattern OTP_CODE_PATTERN = Pattern.compile("\\b(\\d{6})\\b"); + + private enum OtpAuthenticationEntryPoint { + CONTROL_UI, + GAMEPLAY, + VERIFY_EMAIL_OTP, + PLAYER_BOOTSTRAP + } @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -79,7 +92,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private DSLContext dsl; @Autowired private AccountService accountService; @Autowired private AccountRepository accountRepository; - @Autowired private SessionService sessionService; + @MockitoSpyBean private SessionService sessionService; @Autowired private JwtUtil jwtUtil; @MockitoBean private EntityManagementClient entityManagementClient; @@ -163,6 +176,126 @@ void databaseInsertAuthenticationUsesTriggerProvedUuidAndCannotRemapItsSource() .hasMessage("Account not found"); } + @Test + void emailOtpAuthenticationIssuesPersistedUuidAndConsumesTheChallengeExactlyOnce() { + Account persisted = createVerifiedAccount("otp"); + String email = persisted.getEmail(); + UUID expectedAccountUuid = persisted.getAccountUuid(); + assertThat(persisted.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(persisted.getAccountUuidSourceNumericId()).isEqualTo(persisted.getId()); + + String deliveredCode = requestEmailLoginOtpAndCaptureCode(email); + + String wrongCode = wrongOtpCode(deliveredCode); + assertThatThrownBy(() -> accountService.verifyEmailLoginOtp(email, wrongCode)) + .isInstanceOf(AuthenticationException.class) + .hasMessage("Invalid credentials"); + var challengeAfterWrongCode = + challengeRepositorySpy.findByAccountId(persisted.getId()).orElseThrow(); + assertThat(challengeAfterWrongCode.getInvalidAttemptCount()).isEqualTo(1); + assertThat(challengeAfterWrongCode.getCodeHash()).isNotEqualTo(deliveredCode); + assertThat(accountUuidFor(persisted.getId())).isEqualTo(expectedAccountUuid); + + var result = accountService.verifyEmailLoginOtp(email, deliveredCode); + assertThat(jwtUtil.parseToken(result.authToken()).getPayload().getAudience()) + .containsOnly("account-service"); + assertAuthenticationAndPrivateLookup(persisted.getId(), expectedAccountUuid, result); + assertThat(challengeRepositorySpy.findByAccountId(persisted.getId())).isEmpty(); + assertThat(emailLoginChallengeCount(persisted.getId())).isZero(); + + assertThatThrownBy(() -> accountService.verifyEmailLoginOtp(email, deliveredCode)) + .isInstanceOf(AuthenticationException.class) + .hasMessage("Invalid credentials"); + assertThat(accountUuidFor(persisted.getId())).isEqualTo(expectedAccountUuid); + assertThat(emailLoginChallengeCount(persisted.getId())).isZero(); + } + + @Test + void rejectedEmailOtpPersistsChallengeAttemptForControlUiAuthentication() { + assertRejectedEmailOtpPersistsChallengeAttempt(OtpAuthenticationEntryPoint.CONTROL_UI); + } + + @Test + void rejectedEmailOtpPersistsChallengeAttemptForGameplayAuthentication() { + assertRejectedEmailOtpPersistsChallengeAttempt(OtpAuthenticationEntryPoint.GAMEPLAY); + } + + @Test + void rejectedEmailOtpPersistsChallengeAttemptForOtpCompletion() { + assertRejectedEmailOtpPersistsChallengeAttempt(OtpAuthenticationEntryPoint.VERIFY_EMAIL_OTP); + } + + @Test + void rejectedEmailOtpPersistsChallengeAttemptForPlayerBootstrap() { + assertRejectedEmailOtpPersistsChallengeAttempt(OtpAuthenticationEntryPoint.PLAYER_BOOTSTRAP); + } + + private void assertRejectedEmailOtpPersistsChallengeAttempt( + OtpAuthenticationEntryPoint entryPoint) { + Account persisted = createVerifiedAccount("otp-rejected"); + String deliveredCode = requestEmailLoginOtpAndCaptureCode(persisted.getEmail()); + String wrongCode = wrongOtpCode(deliveredCode); + var challengeBeforeWrongCode = + challengeRepositorySpy.findByAccountId(persisted.getId()).orElseThrow(); + + assertThatThrownBy( + () -> attemptEmailOtpAuthentication(entryPoint, persisted.getEmail(), wrongCode)) + .isInstanceOf(AuthenticationException.class) + .hasMessage("Invalid credentials"); + + var challengeAfterWrongCode = + challengeRepositorySpy.findByAccountId(persisted.getId()).orElseThrow(); + assertThat(challengeAfterWrongCode.getInvalidAttemptCount()).isEqualTo(1); + assertThat(challengeAfterWrongCode.getCodeHash()) + .isEqualTo(challengeBeforeWrongCode.getCodeHash()) + .isNotEqualTo(deliveredCode); + assertThat(emailLoginChallengeCount(persisted.getId())).isEqualTo(1L); + assertThat(accountUuidFor(persisted.getId())).isEqualTo(persisted.getAccountUuid()); + assertThat(accountService.resolveAccountStorageId(persisted.getAccountUuid())) + .isEqualTo(persisted.getId()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeAccountSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + } + + @Test + void nonAuthenticationSessionFailureRollsBackOtpConsumption() { + Account persisted = createVerifiedAccount("otp-store"); + String deliveredCode = requestEmailLoginOtpAndCaptureCode(persisted.getEmail()); + var challengeBeforeFailure = + challengeRepositorySpy.findByAccountId(persisted.getId()).orElseThrow(); + doAnswer( + invocation -> { + throw new IllegalStateException("simulated session storage failure"); + }) + .when(sessionService) + .storeAccountSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + + assertThatThrownBy( + () -> accountService.verifyEmailLoginOtp(persisted.getEmail(), deliveredCode)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("simulated session storage failure"); + + ArgumentCaptor tokenCaptor = ArgumentCaptor.forClass(String.class); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession( + org.mockito.ArgumentMatchers.anyLong(), + tokenCaptor.capture(), + org.mockito.ArgumentMatchers.anyLong()); + assertThat(sessionService.isAccountSessionActive(persisted.getId(), tokenCaptor.getValue())) + .isFalse(); + assertThat(challengeRepositorySpy.findByAccountId(persisted.getId())) + .contains(challengeBeforeFailure); + assertThat(emailLoginChallengeCount(persisted.getId())).isEqualTo(1L); + assertThat(accountUuidFor(persisted.getId())).isEqualTo(persisted.getAccountUuid()); + } + @Test void unmappedUuidDeniesProfileMutationEvenWhenBodyNamesAnExistingPrivateRow() { String suffix = UUID.randomUUID().toString(); @@ -210,6 +343,11 @@ void unmappedUuidDeniesProfileMutationEvenWhenBodyNamesAnExistingPrivateRow() { private void assertAuthenticationAndPrivateLookup( String username, long accountId, UUID expectedAccountUuid) { AuthenticationResult result = accountService.authenticate(username, PASSWORD); + assertAuthenticationAndPrivateLookup(accountId, expectedAccountUuid, result); + } + + private void assertAuthenticationAndPrivateLookup( + long accountId, UUID expectedAccountUuid, AuthenticationResult result) { var claims = jwtUtil.parseToken(result.authToken()).getPayload(); assertThat(result.accountId()).isEqualTo(expectedAccountUuid.toString()); @@ -234,6 +372,53 @@ private UUID accountUuidFor(long accountId) { .get(0, UUID.class); } + private long emailLoginChallengeCount(long accountId) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_email_login_challenge WHERE account_id = ?", + accountId) + .fetchOne(0, Long.class), + "Expected challenge count row for account id " + accountId); + } + + private Account createVerifiedAccount(String prefix) { + String username = prefix + "-" + UUID.randomUUID(); + String email = username + "@example.com"; + var created = accountService.createAccount(new CreateAccountRequest(username, email, PASSWORD)); + assertThat(dsl.execute("UPDATE accounts SET email_verified = TRUE WHERE id = ?", created.id())) + .isEqualTo(1); + return accountRepository.findById(created.id()).orElseThrow(); + } + + private String requestEmailLoginOtpAndCaptureCode(String email) { + accountService.requestEmailLoginOtp(email); + + ArgumentCaptor mailCaptor = ArgumentCaptor.forClass(SimpleMailMessage.class); + org.mockito.Mockito.verify(mailSender).send(mailCaptor.capture()); + SimpleMailMessage deliveredMessage = mailCaptor.getValue(); + assertThat(deliveredMessage.getTo()).containsExactly(email); + assertThat(deliveredMessage.getSubject()).isEqualTo("Your FireMUD login code"); + String deliveredBody = + Objects.requireNonNull(deliveredMessage.getText(), "Expected delivered email OTP body"); + Matcher codeMatcher = OTP_CODE_PATTERN.matcher(deliveredBody); + assertThat(codeMatcher.find()).isTrue(); + return codeMatcher.group(1); + } + + private String wrongOtpCode(String deliveredCode) { + return deliveredCode.equals("000000") ? "000001" : "000000"; + } + + private void attemptEmailOtpAuthentication( + OtpAuthenticationEntryPoint entryPoint, String email, String wrongCode) { + switch (entryPoint) { + case CONTROL_UI -> accountService.authenticate(email, wrongCode); + case GAMEPLAY -> accountService.authenticateForGameplay(email, wrongCode); + case VERIFY_EMAIL_OTP -> accountService.verifyEmailLoginOtp(email, wrongCode); + case PLAYER_BOOTSTRAP -> accountService.issuePlayerBootstrap(email, wrongCode); + } + } + private String profileRowJson(long accountId) { return Objects.requireNonNull( dsl.fetchOne( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 2af7e66166..28552b559c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -408,6 +408,7 @@ void createAccountMapsSpringDataIntegrityConflict() { void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -596,6 +597,7 @@ void committedJoinReplayClassifiesReachableMalformedReadbackAsSessionRevoked() { void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -650,6 +652,7 @@ void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguous) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -731,6 +734,7 @@ void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguou void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -787,6 +791,7 @@ void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -855,6 +860,7 @@ void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { void pairAuthorityPreparationFailureRetainsRetryablePolicyIndependentJoinIntent() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -976,6 +982,7 @@ void pairAuthorityPreparationFailureRetainsRetryablePolicyIndependentJoinIntent( void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1022,6 +1029,7 @@ void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { void expiredPersistedPendingJoinRemainsPendingWithoutAuthorityOrMembershipReads() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1137,6 +1145,7 @@ void expiredPersistedPendingJoinRemainsPendingWithoutAuthorityOrMembershipReads( void joinPublicProductionReturnsConflictWhenGlobalRequestIdClaimIsLost() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1208,6 +1217,7 @@ void joinPublicProductionReturnsConflictWhenGlobalRequestIdClaimIsLost() { void quarantinedLegacyMembershipIsNeverRestoredByPublicJoin() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1254,6 +1264,7 @@ private CommittedJoinFixture prepareCommittedJoinOperation( String requestId) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2033,6 +2044,7 @@ void accountJwtMintPathsRemainCanonicalAndConnectTokenFailsClosedWithoutAuthorit void issuePlayerBootstrapReturnsShortLivedToken() { Account account = new Account(); account.setId(7L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); account.setLoginAuthModes("PASSWORD"); @@ -2061,6 +2073,7 @@ void issuePlayerBootstrapReturnsShortLivedToken() { void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { Account emailAccount = new Account(); emailAccount.setId(7L); + setPersistedAuthenticationIdentity(emailAccount); emailAccount.setUsername("email-owner"); emailAccount.setEmail("player@example.com"); emailAccount.setPasswordHash(hash("password")); @@ -2079,6 +2092,7 @@ void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { Account account = new Account(); account.setId(7L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setEmail("demo@example.com"); account.setLoginAuthModes("EMAIL_OTP"); @@ -2218,6 +2232,7 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2254,6 +2269,7 @@ void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2290,6 +2306,7 @@ void listBootstrapRealmsRejectsNoncanonicalRealmIds(String realmId) { void issueConnectTokenRejectsMalformedConnectScopeId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2319,6 +2336,7 @@ void issueConnectTokenRejectsMalformedConnectScopeId() { void issueConnectTokenRejectsBlankConnectScopeId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2348,6 +2366,7 @@ void issueConnectTokenRejectsBlankConnectScopeId() { void issueConnectTokenRejectsNonPositiveConnectScopeClaims() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2401,6 +2420,7 @@ void issueConnectTokenRejectsNonPositiveConnectScopeClaims() { void issueConnectTokenRejectsMalformedConnectScopeClaims() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2455,6 +2475,7 @@ void issueConnectTokenRejectsMalformedConnectScopeClaims() { void issueConnectTokenRejectsNoncanonicalRealmIdClaims(String realmId) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2507,6 +2528,7 @@ void issueConnectTokenRejectsNoncanonicalRealmIdClaims(String realmId) { void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2560,6 +2582,7 @@ void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { void issueConnectTokenRejectsBlankWorldSlugConnectScopeClaims() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2613,6 +2636,7 @@ void issueConnectTokenRejectsBlankWorldSlugConnectScopeClaims() { void issueConnectTokenRejectsZeroPointerVersionInConnectScopeClaims() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -2827,6 +2851,7 @@ void getTenantEntitlementsForRuntimeTreatsMixedSubscriptionRowsAsUnavailable() { void issueConnectTokenFailsClosedWithoutCompleteSelectedTargetAuthorityEvidence() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3005,6 +3030,7 @@ void issueConnectTokenRequiresActiveMembershipForNonPublicRealm() { void issueConnectTokenRetriesAfterEntitlementAuthorityRecoversWithoutCachingFailure() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3060,6 +3086,7 @@ void issueConnectTokenRetriesAfterEntitlementAuthorityRecoversWithoutCachingFail void issueConnectTokenRejectsStaleAdmissionPointerAfterBootstrapDiscovery() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3114,6 +3141,7 @@ void issueConnectTokenRejectsStaleAdmissionPointerAfterBootstrapDiscovery() { void issueConnectTokenRejectsWorldMismatchAfterBootstrapDiscovery() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3165,6 +3193,7 @@ void issueConnectTokenRejectsWorldMismatchAfterBootstrapDiscovery() { void issueConnectTokenResolvesAdmissionRoutingBeforeEntitlementEvaluation() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3227,6 +3256,7 @@ void issueConnectTokenResolvesAdmissionRoutingBeforeEntitlementEvaluation() { void issueConnectTokenDoesNotReplayCachedLegacySuccess() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3318,6 +3348,7 @@ void issueConnectTokenRejectsCachedLegacySuccessForNonPublicRealm() { void issueConnectTokenRequiresExplicitPublicProductionMembership() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3371,6 +3402,7 @@ void issueConnectTokenRequiresExplicitPublicProductionMembership() { void issueConnectTokenRejectsMissingMembershipWhenPublicJoiningIsDisabled() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3403,6 +3435,7 @@ void issueConnectTokenRejectsMissingMembershipWhenPublicJoiningIsDisabled() { void issueConnectTokenClassifiesKnownBillingDenialAndReplaysItDeterministically() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3470,6 +3503,7 @@ void issueConnectTokenRejectsPresentNonAdmittingMembership( boolean publicProductionRealm, String realmSlug) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); if (!publicProductionRealm) { @@ -3583,6 +3617,7 @@ void issueConnectTokenRejectsPresentNonAdmittingMembership( void issueConnectTokenReplaysSameFailureForSameRequestId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3673,6 +3708,7 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { void listBootstrapCharactersUsesEntityManagementForResolvedRealm() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3716,6 +3752,7 @@ void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( boolean membershipExists) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3763,6 +3800,7 @@ void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( void listBootstrapCharactersChecksPublicJoinPolicyBeforeReturningJoinRequired() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3797,6 +3835,7 @@ void listBootstrapCharactersChecksPublicJoinPolicyBeforeReturningJoinRequired() void listBootstrapCharactersReturnsEntitlementUnavailableBeforeClassifyingMembership() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3876,6 +3915,7 @@ void listBootstrapCharactersRejectsLegacyGrantWithoutLifecycleProof() { void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3929,6 +3969,7 @@ void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { void listBootstrapCharactersSkipsMalformedUnrelatedRealm() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3978,6 +4019,7 @@ void listBootstrapCharactersSkipsMalformedUnrelatedRealm() { void listBootstrapRealmsIncludesRealmStatePolicy() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4006,6 +4048,7 @@ void listBootstrapRealmsIncludesRealmStatePolicy() { void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4060,6 +4103,7 @@ void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { void listBootstrapCharactersUsesIsolatedRealmRoster() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4135,6 +4179,7 @@ void listBootstrapCharactersUsesIsolatedRealmRoster() { void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4183,6 +4228,7 @@ void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4231,6 +4277,7 @@ void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicatesAcrossWorlds() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4329,6 +4376,7 @@ void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicat void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4404,6 +4452,7 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { void listBootstrapCharactersRejectsPathThatDoesNotMatchSignedScope() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4431,6 +4480,7 @@ void listBootstrapCharactersRejectsPathThatDoesNotMatchSignedScope() { void listBootstrapCharactersRejectsChangedCanonicalRealmId() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4469,6 +4519,7 @@ void listBootstrapCharactersRejectsChangedCanonicalRealmId() { void listBootstrapRealmsExcludesNonPublicRealmWithoutGrant() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4517,6 +4568,7 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( boolean visible, boolean publicProductionRealm) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4581,6 +4633,7 @@ void listBootstrapRealmsDoesNotUseLegacyGrantAsLifecycleProof( boolean visible, boolean publicProductionRealm) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4642,6 +4695,7 @@ void listBootstrapRealmsExcludesInactiveMembershipDespiteAdmissionFlag( boolean publicProductionRealm) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5436,6 +5490,7 @@ private PrivateConnectTokenContext preparePrivateConnectTokenContext( private PrivateConnectTokenContext preparePrivateConnectTokenContext( Account account, boolean grantAtIssuance, String membershipLifecycleState) { + setPersistedAuthenticationIdentity(account); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); AccountTenantMembership tenantMembership = membership(account, 7L); @@ -5503,6 +5558,7 @@ private PrivateConnectTokenContext preparePrivateConnectTokenContext( private PrivateConnectTokenContext preparePublicInactiveConnectTokenContext( Account account, boolean publicJoiningAllowed) { + setPersistedAuthenticationIdentity(account); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); AccountTenantMembership tenantMembership = membership(account, 7L); From 56a222bf289caa710285bf8655eee1d04161b22e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 04:56:26 +1300 Subject: [PATCH 10/23] fix(account): carry proved UUID through bootstrap and connect scopes --- .github/workflows/ci.yml | 3 + .../account-service/api-contracts.md | 2 +- design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 4 +- .../dto/PlayerBootstrapResult.java | 2 +- .../service/impl/AccountServiceImpl.java | 126 +++++++--- .../src/main/resources/openapi.yaml | 4 +- ...ountAuthenticationUuidIntegrationTest.java | 102 ++++++++ .../controller/AuthControllerTest.java | 5 +- .../PublicBootstrapRoutesProdProfileTest.java | 5 +- .../service/impl/AccountServiceImplTest.java | 237 +++++++++++++++--- 11 files changed, 414 insertions(+), 81 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 438a06bf14..b6f89deed1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1004,6 +1004,9 @@ jobs: --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#databaseInsertAuthenticationUsesTriggerProvedUuidAndCannotRemapItsSource()' \ --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#unmappedUuidDeniesProfileMutationEvenWhenBodyNamesAnExistingPrivateRow()' \ --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#emailOtpAuthenticationIssuesPersistedUuidAndConsumesTheChallengeExactlyOnce()' \ + --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#playerBootstrapEmailOtpCarriesPersistedUuidAndConsumesChallengeExactlyOnce()' \ + --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#bootstrapConsumerRejectsUnmappedAccountUuidBeforeSessionLookup()' \ + --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#bootstrapConnectScopeRejectsUnmappedAccountUuidBeforeScopeUse()' \ --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#rejectedEmailOtpPersistsChallengeAttemptForControlUiAuthentication()' \ --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#rejectedEmailOtpPersistsChallengeAttemptForGameplayAuthentication()' \ --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#rejectedEmailOtpPersistsChallengeAttemptForOtpCompletion()' \ diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index cef434cd22..b74ba623c4 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -60,7 +60,7 @@ The hosted Creator Party, terms catalog, acceptance/currentness evidence, and ch The current credential-granting `Authenticate`, `RequestEmailLoginOtp`, and `VerifyEmailLoginOtp` gRPC handlers require the exact authenticated Game Session mTLS peer before credential or challenge work; the shared public-method list still bypasses bearer validation for these methods, so the peer guard is required and is not a JWT fallback. Legacy profile GET/PUT now require the exact Social Groups peer and a non-internal caller subject matching the requested account; presence-policy batch reads require the exact Social Groups peer and read only tenant-scoped profiles. The account-ID export, external-link, and verification gRPC handlers deny before data access or mutation because no authorized caller contract exists. Runtime membership, grant, and entitlement methods deny before Account reads until typed player/target binding is available; these local guards are not complete admission proof. `GetBalance`, `AddCurrency`, and `SpendCurrency` now return `FAILED_PRECONDITION` before balance access or mutation because virtual currency is a deferred substrate, not a supported v1 API. -The authentication response's `accountId` is the canonical non-nil UUID required by [Identifier Glossary](../../system-architecture-identifier-glossary.md); Account must prove the exact persisted `account_uuid`, recognized provenance and unchanged numeric source row before issuing the result or consuming a successful challenge. `Authenticate`, email-OTP completion and REST `/auth/login` carry that same UUID, and the token's subject and Account identity claim carry it under the [JWT owner](../../system-architecture-jwt-and-token-contracts.md). The numeric Account primary key remains an Account-local storage selector, never an alternate wire identity. A missing or contradictory source denies credential creation; no tenant association or admission follows from proving global Account identity. The complete consumer, registry and activation proof remains separately tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). +The authentication response's `accountId` is the canonical non-nil UUID required by [Identifier Glossary](../../system-architecture-identifier-glossary.md); Account must prove the exact persisted `account_uuid`, recognized provenance and unchanged numeric source row before issuing the result or consuming a successful challenge. `Authenticate`, email-OTP completion, REST `/auth/login` and `/auth/player-bootstrap` carry that same UUID, and each token's subject and Account identity claim carry it under the [JWT owner](../../system-architecture-jwt-and-token-contracts.md). Account's client-readable bootstrap connect-scope token also binds that exact Account UUID; its owner-local reader validates the subject/claim match and source readback before recovering any private storage selector. The numeric Account primary key remains an Account-local storage selector, never an alternate wire identity. A missing or contradictory source denies credential creation; no tenant association or admission follows from proving global Account identity. Numeric tenant/catalog and other cross-owner consumers, complete token registry and activation proof remain separately tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). Fresh-tenant identity adds no public Account endpoint or membership shortcut. The #2915 consumer uses Account's authenticated normal workload to read exact Game Design creation evidence, then commits an immutable canonical-UUID association and shared UUID conflict claim before using the existing no-reset tenant-generation initialization; it neither infers a retained numeric key nor admits a player. Exact #2915 head `910d0a6f41d60ee7214b610d56f89c51db260413` [CI 36796087279](https://github.com/benhook1013/FireMUD/actions/runs/36796087279) executed and passed all six Account fresh-association and seven Game Design creation PostgreSQL cases without skips, including retry, concurrency and rollback. This corrected component proof supersedes the earlier schema-fixture failure; it does not prove deployed workload identity, a live cross-owner handoff or activation. Detailed proof and remaining gates belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). The Game Design wire and digest remain owned by its [API contract](../game-design-service/api-contracts.md#fresh-tenant-creation-operation-and-account-readback), and Account's local storage/readback consequence is described in [Runtime & Data](./runtime-and-data.md). The membership RPC remains denied. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 0ebb6065a9..77c0f7df39 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -184,3 +184,8 @@ Entry format: - Context: repeated Account PostgreSQL fixtures supplied `Long.class` or `UUID.class` to `DSLContext.fetchValue(String, Object...)` as if that SQL overload selected a return type. - Observation: the class is a bind argument, not a type selector; compilation alone did not prove correct SQL binding. Integration inspection corrected the fixtures before claiming execution. - Expected pattern: bind only actual SQL parameters with `resultQuery(sql, parameters)`, then use `fetchOne(columnIndex, type)` for typed extraction and an explicit required-row check where absence is impossible. Retain separate PostgreSQL execution proof; analyzer or compiler success is not that proof. + +- `2026-10-02`: Use the affected SpotBugs task's detailed log when no report is emitted + - Context: an Account `fullCheck` failed at `spotbugsTest` with exit code 1 but no report artifact or finding in the normal log. + - Observation: rerunning the affected canonical task with `-PfullCheck --info` exposed the exact unused-method finding. The obsolete numeric assertion helper was removed and the consolidated gate rerun; no analyzer suppression or disabled check was needed. + - Expected pattern: inspect the affected task's detailed output before searching for a report that its configuration does not emit, and keep the diagnostic run separate from the final consolidated proof. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 1f796d059c..53d123fb27 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -16,7 +16,9 @@ The existing membership-client UUID guard now uses a shared Game Session `Accoun Corrected exact head `acd7693e7c727a16bc68f89c8f74c62415001463` [CI36875629815](https://github.com/benhook1013/FireMUD/actions/runs/36875629815) passed strict Account authentication3/3 and Game Session command UUID storage/migration5/5 with zero skips, failures or errors. This resolves the earlier exception-fixture failure, not wider job or runtime readiness. Aggregate CI remained FAILURE. Its two broader Account HTTP test failures were stale numeric-identity fixtures: malformed Account input expected the old numeric error, and a tenant-zero test used a numeric path/subject that failed the UUID guard first. The corrected fixtures preserve the exact status/error and tenant guard assertions. Python lint, the dev-demo summary contract, Automation formatting, TCP cross-service and Game Design EntityDigest also failed; the broader Game Session job was cancelled after component proof. The separate unpublished carrier tree now passes its full local Game Session check/JAR after exact UUID fixture corrections: 1,752 unit, 18 non-PostgreSQL integration and one cross-service case executed without failures/errors; 17 unit, 133 integration and 33 cross-service cases skipped. That local proof neither supplies PostgreSQL execution nor permits an over-ceiling publication. -The subsequent Account batch corrects the existing email-OTP throw-after-write transaction defect: rejected attempts and exhausted/expired challenge cleanup survive `AuthenticationException` at the four authentication entrypoints, while non-authentication session-storage failure still rolls back challenge consumption. Bootstrap also proves persisted Account identity before consuming a successful challenge; its remaining numeric token/DTO carrier is still an explicit migration obligation, not a UUID-complete bootstrap claim. Six additional PostgreSQL cases exercise actual OTP delivery/challenge persistence, exact persisted UUID issuance/one-use consumption, durable wrong-code counters at all four entrypoints, and non-authentication rollback. The mandatory early CI gate now requires all nine UUID/OTP cases plus the two corrected HTTP assertions. Local full Account check/JAR, Java formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown passed (70 tasks, 18 executed/52 up-to-date), with 502 unit executions and zero skips/failures/errors. All 155 PostgreSQL cases compiled/discovered but skipped without Docker; the new nine-plus-two component requires exact-head runner execution. Historical three-case execution does not prove this batch. Activation gates remain closed. +The subsequent Account batch corrects the existing email-OTP throw-after-write transaction defect: rejected attempts and exhausted/expired challenge cleanup survive `AuthenticationException` at the four authentication entrypoints, while non-authentication session-storage failure still rolls back challenge consumption. Bootstrap proves persisted Account identity before consuming a successful challenge. Six additional PostgreSQL cases exercise actual OTP delivery/challenge persistence, exact persisted UUID issuance/one-use consumption, durable wrong-code counters at all four entrypoints, and non-authentication rollback. Local full Account check/JAR, Java formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown passed (70 tasks, 18 executed/52 up-to-date), with 502 unit executions and zero skips/failures/errors. All 155 PostgreSQL cases compiled/discovered but skipped without Docker. Exact source head `6e5fc2321b582ef5e74962968fa1b069b87b263e` [CI36882689311](https://github.com/benhook1013/FireMUD/actions/runs/36882689311) subsequently executed the required nine UUID/OTP and two HTTP assertions once each, all with zero skips/failures/errors, and the full Account job succeeded. Game Session's five command UUID storage/migration cases also passed strictly. Aggregate CI remained FAILURE: wider Game Session was cancelled after 18 Communication WebSocket assertions, with TCP13/17, Automation8/69, Game Design duplicate-9301, shared summary and Ruff10 failures. The shared summary validator passes on freshly fetched `develop` `24de13120e2778478b25559bfb4cb1d3315b85e2`, so that failure is a concrete older-ancestry reconciliation gap, not a new shared repair. + +The next Account carrier correction makes `PlayerBootstrapResult`, the bootstrap JWT and the client-readable connect-scope token carry the same exact persisted Account UUID. Owner-local readers require canonical string shape, subject/claim equality and unchanged provenance-backed source readback before using the private Account key for storage/session checks; they accept no numeric alias. Local source fixtures and three additional PostgreSQL cases cover bootstrap OTP UUID/one-use issuance and unmapped bootstrap/scope rejection. Full local Account check/JAR and docs passed (70 tasks, 18 executed/52 up-to-date), with 506 unit executions and zero skips/failures/errors; all 158 PostgreSQL cases compiled/discovered but skipped without Docker. The obsolete numeric-only assertion helper was removed after SpotBugs identified it as unused, without suppressing the analyzer or weakening proof. Workflow lint and the 23-case CI-scope contract also passed. The early runner gate now requires all twelve UUID/OTP/bootstrap cases and the two corrected HTTP assertions. These added cases and changed carrier code are excluded from executed `6e5fc2321` proof; exact runner execution remains pending. Tenant/catalog, Entity character discovery, full token registry and cross-owner credential/admission proof remain open. Activation gates remain closed. Exact published receiver head `2e37b38f5fc022844f97ce654e4678771c620376` [CI36858344954](https://github.com/benhook1013/FireMUD/actions/runs/36858344954) completed FAILURE overall but passed both mandatory Game Session PostgreSQL component gates: intake5, snapshot3 and association9 all executed with zero skips/failures/errors; all seven required new snapshot/association methods executed once and passed. This proves the component source fence, exact immutable association, concurrency, lost-response retry and rollback cases that skipped locally, not a live authenticated handoff or admission. The broader Game Session check was subsequently cancelled and is not green. Evidence is the strict runner JUnit verifier output; downloaded failure artifacts are HTML, not raw JUnit XML. Game Design's dedicated association9 suite also passed. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/PlayerBootstrapResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/PlayerBootstrapResult.java index a029e6da93..d3eb6d032f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/PlayerBootstrapResult.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/PlayerBootstrapResult.java @@ -2,4 +2,4 @@ /** Result of issuing a short-lived first-party bootstrap token. */ public record PlayerBootstrapResult( - long accountId, String bootstrapToken, String issuedAt, String expiresAt) {} + String accountId, String bootstrapToken, String issuedAt, String expiresAt) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 0f9939ad29..5bf6aa60dc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -422,14 +422,20 @@ public PlayerBootstrapResult issuePlayerBootstrap(String accountIdentifier, Stri long expiresAt = issuedAt + tokenProperties.getPlayerBootstrapExpirationMs(); String bootstrapToken = mintToken( - String.valueOf(account.getId()), + account.getAccountUuid().toString(), tokenProperties.getPlayerBootstrapExpirationMs(), - Map.of("aud", "player-bootstrap", "accountId", account.getId(), "jti", jti)); + Map.of( + "aud", + "player-bootstrap", + "accountId", + account.getAccountUuid().toString(), + "jti", + jti)); sessionService.storeAccountSession( account.getId(), bootstrapToken, tokenProperties.getPlayerBootstrapExpirationMs()); logger.info("Issued player bootstrap token for account {}", account.getId()); return new PlayerBootstrapResult( - account.getId(), + account.getAccountUuid().toString(), bootstrapToken, Instant.ofEpochMilli(issuedAt).toString(), Instant.ofEpochMilli(expiresAt).toString()); @@ -543,7 +549,9 @@ public DirectTextJoinScope issueDirectTextConnectScope( || !caller.playableStateScope().equals(target.playableStateScope())) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); } - requireAuthenticationEligible(requireAccount(caller.accountId())); + Account persistedCaller = requireAccount(caller.accountId()); + requireAuthenticationEligible(persistedCaller); + UUID callerAccountUuid = requirePersistedAccountUuid(persistedCaller); RuntimeRealmTarget current = requireRealmTarget(target.tenantId(), target.worldSlug(), target.realmSlug()); if (!isPublicProductionRealm(current)) { @@ -562,7 +570,10 @@ public DirectTextJoinScope issueDirectTextConnectScope( Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); String scopeId = mintAndRetainConnectScope( - new BootstrapContext(caller.accountId()), current, evaluatedAt, expiresAt); + new BootstrapContext(callerAccountUuid, caller.accountId()), + current, + evaluatedAt, + expiresAt); return new DirectTextJoinScope(scopeId, expiresAt.toString()); } @@ -578,7 +589,9 @@ public JoinPublicProductionResult joinPublicProductionFromGameSession( throw new AuthenticationException( "CONNECT_CONTEXT_INVALID", "JOIN caller context is missing"); } - requireAuthenticationEligible(requireAccount(caller.accountId())); + Account persistedCaller = requireAccount(caller.accountId()); + requireAuthenticationEligible(persistedCaller); + requirePersistedAccountUuid(persistedCaller); return joinPublicProductionForTrustedCaller( caller.accountId(), caller.sessionId(), caller, request); } @@ -1158,20 +1171,24 @@ private void recordJoinAttemptFailureAfterRollback(String requestId, String fail private void validateDirectTextJoinScope( DirectTextCallerContext caller, VerifiedJoinScope scope) { - if (caller != null - && (caller.accountId() != scope.accountId() - || caller.tenantId() != scope.tenantId() - || !caller.realmId().equals(scope.realmId()) - || caller.gameInstanceId() != scope.gameInstanceId() - || !caller.playableStateNamespaceId().equals(scope.playableStateNamespaceId()) - || !caller.playableStateScope().equals(scope.playableStateScope()))) { - throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + if (caller != null) { + requirePersistedAccountUuid(requireAccount(caller.accountId())); + if (caller.accountId() != scope.accountId() + || caller.tenantId() != scope.tenantId() + || !caller.realmId().equals(scope.realmId()) + || caller.gameInstanceId() != scope.gameInstanceId() + || !caller.playableStateNamespaceId().equals(scope.playableStateNamespaceId()) + || !caller.playableStateScope().equals(scope.playableStateScope())) { + throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); + } } } private JoinEvaluation evaluateJoin(VerifiedJoinScope scope) { + UUID accountUuid = requirePersistedAccountUuid(requireAccount(scope.accountId())); return evaluateJoin( new ConnectScopeContext( + accountUuid, scope.accountId(), scope.tenantId(), scope.realmId(), @@ -1483,15 +1500,18 @@ private BootstrapContext requireBootstrapContext(String bootstrapToken) { "CONNECT_CONTEXT_INVALID", "Missing bootstrap token", "Invalid bootstrap token"); + UUID accountUuid; + long accountId; try { - long accountId = requireSignedActorAccountId(claims); - if (!sessionService.isAccountSessionActive(accountId, bootstrapToken)) { - throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Bootstrap token expired"); - } - return new BootstrapContext(accountId); - } catch (IllegalArgumentException ex) { + accountUuid = requireSignedActorAccountUuid(claims); + accountId = resolveAccountStorageId(accountUuid); + } catch (IllegalArgumentException | IllegalStateException ex) { throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Invalid bootstrap token", ex); } + if (!sessionService.isAccountSessionActive(accountId, bootstrapToken)) { + throw new AuthenticationException("CONNECT_CONTEXT_INVALID", "Bootstrap token expired"); + } + return new BootstrapContext(accountUuid, accountId); } private RuntimeRealmTarget requireAdmissibleRealm( @@ -1595,11 +1615,11 @@ private String mintConnectScopeId( Instant expiresAt) { long expirationMs = Math.max(1L, expiresAt.toEpochMilli() - evaluatedAt.toEpochMilli()); return mintToken( - String.valueOf(bootstrapContext.accountId()), + bootstrapContext.accountUuid().toString(), expirationMs, Map.ofEntries( Map.entry("aud", "bootstrap-connect-scope"), - Map.entry("accountId", bootstrapContext.accountId()), + Map.entry("accountId", bootstrapContext.accountUuid().toString()), Map.entry("tenantId", realm.tenantId()), Map.entry("realmId", realm.realmId().toString()), Map.entry("worldSlug", realm.worldSlug()), @@ -1615,7 +1635,7 @@ private String mintConnectScopeId( "jti", stableId( "connect-scope", - bootstrapContext.accountId(), + bootstrapContext.accountUuid().toString(), Long.toString(realm.tenantId()), realm.worldSlug(), realm.realmSlug(), @@ -1672,9 +1692,8 @@ private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { INVALID_CONNECT_SCOPE_MESSAGE, INVALID_CONNECT_SCOPE_MESSAGE); try { - JwtClaims.SignedGameplayRoutingClaims routingClaims = - JwtClaims.requireSignedGameplayRoutingClaims( - claims, "signed token account subject mismatch"); + UUID accountUuid = requireSignedActorAccountUuid(claims); + long accountId = resolveAccountStorageId(accountUuid); Instant connectScopeExpiresAt = parseInstant(claims.get("connectScopeExpiresAt")); Instant evaluatedAt = parseInstant(claims.get("evaluatedAt")); if (connectScopeExpiresAt == null) { @@ -1684,25 +1703,46 @@ private ConnectScopeContext requireConnectScopeContext(String connectScopeId) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE); } return new ConnectScopeContext( - routingClaims.accountId(), - routingClaims.tenantId(), + accountUuid, + accountId, + JwtClaims.requireLong(claims.get("tenantId"), "tenantId", false), requireCanonicalRealmId(claims.get("realmId")), - routingClaims.worldSlug(), - routingClaims.realmSlug(), + JwtClaims.requireText(claims.get("worldSlug"), "worldSlug"), + JwtClaims.requireText(claims.get("realmSlug"), "realmSlug"), JwtClaims.requireText(claims.get("playableStateNamespaceId"), "playableStateNamespaceId"), JwtClaims.requireText(claims.get("playableStateScope"), "playableStateScope"), - routingClaims.gameInstanceId(), + JwtClaims.requireLong(claims.get("gameInstanceId"), "gameInstanceId", false), requirePositiveLong(claims.get("catalogRevision"), "catalogRevision"), - routingClaims.pointerVersion(), + JwtClaims.requireLong(claims.get("pointerVersion"), "pointerVersion", false), evaluatedAt, connectScopeExpiresAt); - } catch (IllegalArgumentException ex) { + } catch (IllegalArgumentException | IllegalStateException ex) { throw new AuthenticationException("CONNECT_SCOPE_INVALID", INVALID_CONNECT_SCOPE_MESSAGE, ex); } } - private static long requireSignedActorAccountId(Claims claims) { - return JwtClaims.requireSignedActorAccountId(claims, "signed token account subject mismatch"); + private static UUID requireSignedActorAccountUuid(Claims claims) { + UUID subjectAccountUuid = requireCanonicalAccountUuid(claims.getSubject(), "sub"); + UUID claimedAccountUuid = requireCanonicalAccountUuid(claims.get("accountId"), "accountId"); + if (!subjectAccountUuid.equals(claimedAccountUuid)) { + throw new IllegalArgumentException("signed token account subject mismatch"); + } + return claimedAccountUuid; + } + + private static UUID requireCanonicalAccountUuid(Object value, String claimName) { + if (!(value instanceof String text)) { + throw new IllegalArgumentException(claimName + " must be a canonical Account UUID"); + } + try { + UUID accountUuid = UUID.fromString(text); + if (!accountUuid.toString().equals(text) || NIL_ACCOUNT_UUID.equals(accountUuid)) { + throw new IllegalArgumentException(claimName + " must be a canonical Account UUID"); + } + return accountUuid; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException(claimName + " must be a canonical Account UUID", ex); + } } private Claims requireSignedTokenClaims( @@ -1732,7 +1772,8 @@ private Claims requireSignedTokenClaims( private void validateConnectScopeAgainstBootstrap( BootstrapContext bootstrapContext, ConnectScopeContext scopeContext) { - if (scopeContext.accountId() != bootstrapContext.accountId()) { + if (!scopeContext.accountUuid().equals(bootstrapContext.accountUuid()) + || scopeContext.accountId() != bootstrapContext.accountId()) { throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); } } @@ -1908,6 +1949,16 @@ private Account requireAccount(Long accountId) { .orElseThrow(() -> new IllegalArgumentException("Account not found")); } + private UUID requirePersistedAccountUuid(Account account) { + requireAuthenticationPersistedIdentity(account); + UUID accountUuid = account.getAccountUuid(); + if (!account.getId().equals(resolveAccountStorageId(accountUuid))) { + throw new IllegalStateException( + "Account UUID readback did not match its exact persisted source row"); + } + return accountUuid; + } + private boolean hasRealmAccessGrant( Long accountId, Long tenantId, String worldSlug, String realmSlug) { // The retained four-field row cannot prove the current playtest lifecycle and state generation. @@ -2343,7 +2394,7 @@ public void afterCommit() { }); } - private record BootstrapContext(long accountId) {} + private record BootstrapContext(UUID accountUuid, long accountId) {} private record JoinAuditPayload( long accountId, @@ -2489,6 +2540,7 @@ private UUID requireCanonicalRealmId(Object value) { } private record ConnectScopeContext( + UUID accountUuid, long accountId, long tenantId, UUID realmId, diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index d2032f141e..ab4a946695 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -104,7 +104,9 @@ components: type: object properties: accountId: - type: integer + type: string + format: uuid + description: Canonical non-nil persisted Account UUID; never the numeric database primary key. bootstrapToken: type: string issuedAt: diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java index 4f7a02e8ae..b21cafba3f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java @@ -211,6 +211,108 @@ void emailOtpAuthenticationIssuesPersistedUuidAndConsumesTheChallengeExactlyOnce assertThat(emailLoginChallengeCount(persisted.getId())).isZero(); } + @Test + void playerBootstrapEmailOtpCarriesPersistedUuidAndConsumesChallengeExactlyOnce() { + Account persisted = createVerifiedAccount("bootstrap-otp"); + UUID expectedAccountUuid = persisted.getAccountUuid(); + String deliveredCode = requestEmailLoginOtpAndCaptureCode(persisted.getEmail()); + + var result = accountService.issuePlayerBootstrap(persisted.getEmail(), deliveredCode); + + assertThat(result.accountId()) + .isEqualTo(expectedAccountUuid.toString()) + .isNotEqualTo(Long.toString(persisted.getId())); + var claims = jwtUtil.parseToken(result.bootstrapToken()).getPayload(); + assertThat(claims.getSubject()).isEqualTo(expectedAccountUuid.toString()); + assertThat(claims.get("accountId")) + .isInstanceOf(String.class) + .isEqualTo(expectedAccountUuid.toString()); + assertThat(accountService.resolveAccountStorageId(expectedAccountUuid)) + .isEqualTo(persisted.getId()); + assertThat(challengeRepositorySpy.findByAccountId(persisted.getId())).isEmpty(); + assertThat(emailLoginChallengeCount(persisted.getId())).isZero(); + assertThat(sessionService.isAccountSessionActive(persisted.getId(), result.bootstrapToken())) + .isTrue(); + + assertThatThrownBy( + () -> accountService.issuePlayerBootstrap(persisted.getEmail(), deliveredCode)) + .isInstanceOf(AuthenticationException.class) + .hasMessage("Invalid credentials"); + assertThat(challengeRepositorySpy.findByAccountId(persisted.getId())).isEmpty(); + assertThat(emailLoginChallengeCount(persisted.getId())).isZero(); + assertThat(sessionService.isAccountSessionActive(persisted.getId(), result.bootstrapToken())) + .isTrue(); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.times(1)) + .storeAccountSession( + org.mockito.ArgumentMatchers.eq(persisted.getId()), + org.mockito.ArgumentMatchers.eq(result.bootstrapToken()), + org.mockito.ArgumentMatchers.anyLong()); + } + + @Test + void bootstrapConsumerRejectsUnmappedAccountUuidBeforeSessionLookup() { + UUID unmappedAccountUuid = UUID.randomUUID(); + String token = + jwtUtil.generateToken( + unmappedAccountUuid.toString(), + Map.of("aud", "player-bootstrap", "accountId", unmappedAccountUuid.toString())); + + assertThatThrownBy(() -> accountService.listBootstrapWorlds(token)) + .isInstanceOf(AuthenticationException.class) + .hasMessage("Invalid bootstrap token"); + + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .isAccountSessionActive(anyLong(), org.mockito.ArgumentMatchers.anyString()); + } + + @Test + void bootstrapConnectScopeRejectsUnmappedAccountUuidBeforeScopeUse() { + Account persisted = createVerifiedAccount("boot-scope"); + var bootstrap = accountService.issuePlayerBootstrap(persisted.getEmail(), PASSWORD); + UUID unmappedAccountUuid = UUID.randomUUID(); + java.time.Instant evaluatedAt = java.time.Instant.now(); + String connectScope = + jwtUtil.generateToken( + unmappedAccountUuid.toString(), + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", unmappedAccountUuid.toString()), + Map.entry("tenantId", "98123"), + Map.entry("realmId", UUID.randomUUID().toString()), + Map.entry("worldSlug", "demo"), + Map.entry("realmSlug", "production"), + Map.entry("playableStateNamespaceId", "namespace-1"), + Map.entry("playableStateScope", "SHARED"), + Map.entry("gameInstanceId", "123"), + Map.entry("catalogRevision", "1"), + Map.entry("pointerVersion", "1"), + Map.entry("evaluatedAt", evaluatedAt.toString()), + Map.entry("connectScopeExpiresAt", evaluatedAt.plusSeconds(60).toString()), + Map.entry("jti", "unmapped-scope"))); + Long connectScopeRowsBefore = + Objects.requireNonNull( + dsl.resultQuery("SELECT COUNT(*) FROM account_connect_scope_records") + .fetchOne(0, Long.class), + "Expected account connect-scope record count"); + + assertThatThrownBy( + () -> + accountService.issueConnectToken( + bootstrap.bootstrapToken(), + new net.firedevops.firemud.accountservice.dto.ConnectTokenRequest( + connectScope, "unmapped-scope-request"))) + .isInstanceOfSatisfying( + AuthenticationException.class, + exception -> assertThat(exception.getCode()).isEqualTo("CONNECT_SCOPE_INVALID")); + assertThat( + Objects.requireNonNull( + dsl.resultQuery("SELECT COUNT(*) FROM account_connect_scope_records") + .fetchOne(0, Long.class), + "Expected account connect-scope record count")) + .isEqualTo(connectScopeRowsBefore); + org.mockito.Mockito.verifyNoInteractions(gameSessionClient, entityManagementClient); + } + @Test void rejectedEmailOtpPersistsChallengeAttemptForControlUiAuthentication() { assertRejectedEmailOtpPersistsChallengeAttempt(OtpAuthenticationEntryPoint.CONTROL_UI); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java index 483a7af433..13bfe0add0 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java @@ -84,10 +84,11 @@ void loginAcceptsExistingOneCharacterPassword() throws Exception { @Test void playerBootstrapReturnsShortLivedToken() throws Exception { PlayerBootstrapRequest request = new PlayerBootstrapRequest("demo", "password"); + String accountUuid = "59a39c43-6829-48b1-8d09-99bfe533d919"; when(accountService.issuePlayerBootstrap("demo", "password")) .thenReturn( new PlayerBootstrapResult( - 1L, "boot123", "2026-03-30T00:00:00Z", "2026-03-30T00:05:00Z")); + accountUuid, "boot123", "2026-03-30T00:00:00Z", "2026-03-30T00:05:00Z")); mockMvc .perform( @@ -96,7 +97,7 @@ void playerBootstrapReturnsShortLivedToken() throws Exception { .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.accountId").value(1)) + .andExpect(jsonPath("$.data.accountId").value(accountUuid)) .andExpect(jsonPath("$.data.bootstrapToken").value("boot123")); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java index fda8d4325e..2df18b7b4c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java @@ -37,10 +37,11 @@ class PublicBootstrapRoutesProdProfileTest { @Test void playerBootstrapRemainsPublicInProdProfile() throws Exception { PlayerBootstrapRequest request = new PlayerBootstrapRequest("demo@example.com", "swordfish"); + String accountUuid = "59a39c43-6829-48b1-8d09-99bfe533d919"; when(accountService.issuePlayerBootstrap("demo@example.com", "swordfish")) .thenReturn( new PlayerBootstrapResult( - 1L, "boot123", "2026-03-30T00:00:00Z", "2026-03-30T00:05:00Z")); + accountUuid, "boot123", "2026-03-30T00:00:00Z", "2026-03-30T00:05:00Z")); mockMvc .perform( @@ -49,7 +50,7 @@ void playerBootstrapRemainsPublicInProdProfile() throws Exception { .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.accountId").value(1)) + .andExpect(jsonPath("$.data.accountId").value(accountUuid)) .andExpect(jsonPath("$.data.bootstrapToken").value("boot123")); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 28552b559c..a65b218357 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -1994,12 +1994,19 @@ void accountJwtMintPathsRemainCanonicalAndConnectTokenFailsClosedWithoutAuthorit PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - assertCanonicalIssuerAndClaims(bootstrap.bootstrapToken(), "player-bootstrap", 11L); + assertEquals(account.getAccountUuid().toString(), bootstrap.accountId()); + assertCanonicalIssuerAndClaims( + bootstrap.bootstrapToken(), "player-bootstrap", account.getAccountUuid().toString()); String connectScopeId = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); var connectScopeClaims = parseClaims(connectScopeId); - assertCanonicalIssuerAndClaims(connectScopeId, "bootstrap-connect-scope", 11L); + assertEquals("firemud-account-service", connectScopeClaims.getIssuer()); + assertEquals("bootstrap-connect-scope", connectScopeClaims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), connectScopeClaims.getSubject()); + assertEquals( + account.getAccountUuid().toString(), connectScopeClaims.get("accountId", String.class)); + assertNotNull(connectScopeClaims.get("jti")); assertEquals("4c4b57d8-e3a2-48fe-9977-e7df0fdce901", connectScopeClaims.get("realmId")); assertEquals(7L, connectScopeClaims.get("tenantId", Long.class)); @@ -2053,7 +2060,7 @@ void issuePlayerBootstrapReturnsShortLivedToken() { PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "password"); - assertEquals(7L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); assertNotNull(result.bootstrapToken()); assertNotNull(result.issuedAt()); assertNotNull(result.expiresAt()); @@ -2064,6 +2071,8 @@ void issuePlayerBootstrapReturnsShortLivedToken() { org.mockito.ArgumentMatchers.eq(300000L)); var claims = new JwtUtil(JWT_SECRET, 300000L).parseToken(result.bootstrapToken()).getPayload(); assertEquals("player-bootstrap", claims.getAudience().iterator().next()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId")); assertFalse(claims.containsKey("tenantId")); assertEquals(300000L, claims.getExpiration().getTime() - claims.getIssuedAt().getTime()); verifyNoInteractions(accountEmailLoginChallengeRepository); @@ -2083,7 +2092,7 @@ void issuePlayerBootstrapPrefersEmailLookupOverCollidingUsername() { PlayerBootstrapResult result = service.issuePlayerBootstrap(" PLAYER@EXAMPLE.COM ", "password"); - assertEquals(7L, result.accountId()); + assertEquals(emailAccount.getAccountUuid().toString(), result.accountId()); org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) .findByUsername(org.mockito.ArgumentMatchers.anyString()); } @@ -2107,7 +2116,10 @@ void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { PlayerBootstrapResult result = service.issuePlayerBootstrap("demo", "123456"); - assertEquals(7L, result.accountId()); + assertEquals(account.getAccountUuid().toString(), result.accountId()); + var claims = parseClaims(result.bootstrapToken()); + assertEquals(account.getAccountUuid().toString(), claims.getSubject()); + assertEquals(account.getAccountUuid().toString(), claims.get("accountId")); org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(accountEmailLoginChallengeRepository); inOrder.verify(accountEmailLoginChallengeRepository).lockAccountChallenge(7L); inOrder.verify(accountEmailLoginChallengeRepository).findByAccountId(7L); @@ -2118,9 +2130,15 @@ void issuePlayerBootstrapAcceptsAndConsumesEmailLoginOtp() { @Test void listBootstrapWorldsRejectsInactiveAccountBootstrapToken() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + UUID accountUuid = account.getAccountUuid(); String bootstrapToken = new JwtUtil(JWT_SECRET, 300000L) - .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "11")); + .generateToken( + accountUuid.toString(), + Map.of("aud", "player-bootstrap", "accountId", accountUuid.toString())); AuthenticationException ex = assertThrows( @@ -2133,9 +2151,10 @@ void listBootstrapWorldsRejectsInactiveAccountBootstrapToken() { @Test void listBootstrapWorldsRejectsMalformedBootstrapTokenAccountClaim() { + String accountUuid = "59a39c43-6829-48b1-8d09-99bfe533d919"; String malformedBootstrapToken = new JwtUtil(JWT_SECRET, 300000L) - .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "abc")); + .generateToken(accountUuid, Map.of("aud", "player-bootstrap", "accountId", "abc")); AuthenticationException ex = assertThrows( @@ -2145,11 +2164,37 @@ void listBootstrapWorldsRejectsMalformedBootstrapTokenAccountClaim() { assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); } + @Test + void listBootstrapWorldsRejectsUnprovedPersistedAccountUuidBeforeSessionLookup() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + UUID accountUuid = account.getAccountUuid(); + account.setAccountUuidSourceNumericId(12L); + when(accountRepository.findByAccountUuid(accountUuid)).thenReturn(Optional.of(account)); + String bootstrapToken = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken( + accountUuid.toString(), + Map.of("aud", "player-bootstrap", "accountId", accountUuid.toString())); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, () -> service.listBootstrapWorlds(bootstrapToken)); + + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + verify(accountRepository).findByAccountUuid(accountUuid); + verifyNoInteractions(sessionService, gameSessionClient); + } + @Test void listBootstrapWorldsRejectsBootstrapTokenAccountSubjectMismatch() { + String subjectUuid = "d51ee4fa-3af3-437c-98dc-a1bd0706dd91"; + String accountUuid = "59a39c43-6829-48b1-8d09-99bfe533d919"; String malformedBootstrapToken = new JwtUtil(JWT_SECRET, 300000L) - .generateToken("12", Map.of("aud", "player-bootstrap", "accountId", "11")); + .generateToken( + subjectUuid, Map.of("aud", "player-bootstrap", "accountId", accountUuid)); AuthenticationException ex = assertThrows( @@ -2160,10 +2205,12 @@ void listBootstrapWorldsRejectsBootstrapTokenAccountSubjectMismatch() { } @Test - void listBootstrapWorldsRejectsNonPositiveBootstrapTokenClaims() { + void listBootstrapWorldsRejectsNonCanonicalBootstrapTokenAccountUuid() { + String accountUuid = "59a39c43-6829-48b1-8d09-99bfe533d919"; String malformedBootstrapToken = new JwtUtil(JWT_SECRET, 300000L) - .generateToken("11", Map.of("aud", "player-bootstrap", "accountId", "0")); + .generateToken( + accountUuid, Map.of("aud", "player-bootstrap", "accountId", " " + accountUuid)); AuthenticationException ex = assertThrows( @@ -2173,10 +2220,52 @@ void listBootstrapWorldsRejectsNonPositiveBootstrapTokenClaims() { assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); } + @Test + void listBootstrapWorldsRejectsNonStringBootstrapTokenAccountUuid() { + String accountUuid = "59a39c43-6829-48b1-8d09-99bfe533d919"; + String malformedBootstrapToken = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken(accountUuid, Map.of("aud", "player-bootstrap", "accountId", 11L)); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(malformedBootstrapToken)); + + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + verifyNoInteractions(accountRepository, sessionService); + } + + @Test + void listBootstrapWorldsRejectsTrimmedUppercaseAndListAccountUuidClaims() { + String accountUuid = "59a39c43-6829-48b1-8d09-99bfe533d919"; + for (Object malformedAccountId : + java.util.List.of( + " " + accountUuid, + accountUuid.toUpperCase(java.util.Locale.ROOT), + java.util.List.of(accountUuid))) { + String malformedBootstrapToken = + new JwtUtil(JWT_SECRET, 300000L) + .generateToken( + accountUuid, Map.of("aud", "player-bootstrap", "accountId", malformedAccountId)); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(malformedBootstrapToken)); + + assertEquals("CONNECT_CONTEXT_INVALID", ex.getCode()); + } + + verifyNoInteractions(accountRepository, sessionService); + } + @Test void listBootstrapWorldsRejectsBootstrapTokenWithoutAudience() { + String accountUuid = "59a39c43-6829-48b1-8d09-99bfe533d919"; String malformedBootstrapToken = - new JwtUtil(JWT_SECRET, 300000L).generateToken("11", Map.of("accountId", "11")); + new JwtUtil(JWT_SECRET, 300000L) + .generateToken(accountUuid, Map.of("accountId", accountUuid)); AuthenticationException ex = assertThrows( @@ -2384,12 +2473,12 @@ void issueConnectTokenRejectsNonPositiveConnectScopeClaims() { String malformedConnectScopeId = new JwtUtil(JWT_SECRET, 120000L) .generateToken( - "11", + account.getAccountUuid().toString(), Map.of( "aud", "bootstrap-connect-scope", "accountId", - "11", + account.getAccountUuid().toString(), "tenantId", "7", "worldSlug", @@ -2438,7 +2527,7 @@ void issueConnectTokenRejectsMalformedConnectScopeClaims() { String malformedConnectScopeId = new JwtUtil(JWT_SECRET, 120000L) .generateToken( - "11", + account.getAccountUuid().toString(), Map.of( "aud", "bootstrap-connect-scope", @@ -2468,6 +2557,38 @@ void issueConnectTokenRejectsMalformedConnectScopeClaims() { new ConnectTokenRequest(malformedConnectScopeId, "req-err3"))); assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); + + String nonStringAccountIdScope = + new JwtUtil(JWT_SECRET, 120000L) + .generateToken( + account.getAccountUuid().toString(), + Map.of( + "aud", + "bootstrap-connect-scope", + "accountId", + 11L, + "tenantId", + "7", + "worldSlug", + "demo", + "realmSlug", + "production", + "gameInstanceId", + "44", + "pointerVersion", + "17", + "connectScopeExpiresAt", + java.time.Instant.now().plusSeconds(3600).toString(), + "jti", + "invalid-type")); + AuthenticationException nonStringClaimException = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(nonStringAccountIdScope, "req-err3-type"))); + assertEquals("CONNECT_SCOPE_INVALID", nonStringClaimException.getCode()); } @ParameterizedTest @@ -2493,10 +2614,10 @@ void issueConnectTokenRejectsNoncanonicalRealmIdClaims(String realmId) { String malformedConnectScopeId = new JwtUtil(JWT_SECRET, 120000L) .generateToken( - "11", + account.getAccountUuid().toString(), Map.ofEntries( Map.entry("aud", "bootstrap-connect-scope"), - Map.entry("accountId", "11"), + Map.entry("accountId", account.getAccountUuid().toString()), Map.entry("tenantId", "7"), Map.entry("realmId", realmId), Map.entry("worldSlug", "demo"), @@ -2543,15 +2664,16 @@ void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String otherAccountUuid = UUID.randomUUID().toString(); String malformedConnectScopeId = new JwtUtil(JWT_SECRET, 120000L) .generateToken( - "12", + otherAccountUuid, Map.of( "aud", "bootstrap-connect-scope", "accountId", - "11", + account.getAccountUuid().toString(), "tenantId", "7", "worldSlug", @@ -2578,6 +2700,56 @@ void issueConnectTokenRejectsConnectScopeAccountSubjectMismatch() { assertEquals("CONNECT_SCOPE_INVALID", ex.getCode()); } + @Test + void issueConnectTokenRejectsScopeBoundToAnotherPersistedAccountUuid() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + Account otherAccount = new Account(); + otherAccount.setId(12L); + setPersistedAuthenticationIdentity(otherAccount); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + java.time.Instant evaluatedAt = java.time.Instant.now(); + String otherAccountUuid = otherAccount.getAccountUuid().toString(); + String otherAccountScope = + new JwtUtil(JWT_SECRET, 120000L) + .generateToken( + otherAccountUuid, + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", otherAccountUuid), + Map.entry("tenantId", "7"), + Map.entry("realmId", REALM_ID), + Map.entry("worldSlug", "demo"), + Map.entry("realmSlug", "production"), + Map.entry("playableStateNamespaceId", "production-namespace-7"), + Map.entry("playableStateScope", "SHARED"), + Map.entry("gameInstanceId", "44"), + Map.entry("catalogRevision", "23"), + Map.entry("pointerVersion", "17"), + Map.entry("evaluatedAt", evaluatedAt.toString()), + Map.entry("connectScopeExpiresAt", evaluatedAt.plusSeconds(60).toString()), + Map.entry("jti", "other-account-scope"))); + + AuthenticationException ex = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), new ConnectTokenRequest(otherAccountScope, "req"))); + + assertEquals("CONNECT_SCOPE_MISMATCH", ex.getCode()); + verify(accountRepository).findByAccountUuid(account.getAccountUuid()); + verify(accountRepository).findByAccountUuid(otherAccount.getAccountUuid()); + verifyNoInteractions(accountTenantMembershipRepository, accountConnectScopeRepository); + } + @Test void issueConnectTokenRejectsBlankWorldSlugConnectScopeClaims() { Account account = new Account(); @@ -2600,12 +2772,12 @@ void issueConnectTokenRejectsBlankWorldSlugConnectScopeClaims() { String malformedConnectScopeId = new JwtUtil(JWT_SECRET, 120000L) .generateToken( - "11", + account.getAccountUuid().toString(), Map.of( "aud", "bootstrap-connect-scope", "accountId", - "11", + account.getAccountUuid().toString(), "tenantId", "7", "worldSlug", @@ -2654,12 +2826,12 @@ void issueConnectTokenRejectsZeroPointerVersionInConnectScopeClaims() { String malformedConnectScopeId = new JwtUtil(JWT_SECRET, 120000L) .generateToken( - "11", + account.getAccountUuid().toString(), Map.of( "aud", "bootstrap-connect-scope", "accountId", - "11", + account.getAccountUuid().toString(), "tenantId", "7", "worldSlug", @@ -5409,15 +5581,6 @@ void updateLoginAuthModesFailsClosedBeforeReadingOrPersistingAccount() { org.mockito.Mockito.verifyNoInteractions(accountRepository); } - private void assertCanonicalIssuerAndClaims( - String token, String expectedAudience, long expectedAccountId) { - var claims = parseClaims(token); - assertEquals("firemud-account-service", claims.getIssuer()); - assertEquals(expectedAudience, claims.getAudience().iterator().next()); - assertEquals(expectedAccountId, claims.get("accountId", Long.class)); - assertNotNull(claims.get("jti")); - } - private void assertCanonicalIssuerAndClaims( String token, String expectedAudience, String expectedAccountUuid) { var claims = parseClaims(token); @@ -5429,19 +5592,21 @@ private void assertCanonicalIssuerAndClaims( assertFalse(claims.containsKey("tenantId")); } - private static void setPersistedAuthenticationIdentity(Account account) { + private void setPersistedAuthenticationIdentity(Account account) { setPersistedAuthenticationIdentity( account, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); } - private static void setPersistedAuthenticationIdentity( + private void setPersistedAuthenticationIdentity( Account account, AccountIdentityProvenance provenance) { account.setAccountUuid(UUID.randomUUID()); account.setAccountUuidProvenance(provenance); account.setAccountUuidSourceNumericId(account.getId()); + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenReturn(Optional.of(account)); } - private static void assignInvalidAuthenticationIdentity( + private void assignInvalidAuthenticationIdentity( Account account, InvalidAuthenticationIdentity failure) { setPersistedAuthenticationIdentity(account); switch (failure) { @@ -5537,11 +5702,11 @@ private PrivateConnectTokenContext preparePrivateConnectTokenContext( String connectScopeId = new JwtUtil(JWT_SECRET, 30000L) .generateToken( - "11", + account.getAccountUuid().toString(), tokenProperties.getConnectScopeExpirationMs(), Map.ofEntries( Map.entry("aud", "bootstrap-connect-scope"), - Map.entry("accountId", 11L), + Map.entry("accountId", account.getAccountUuid().toString()), Map.entry("tenantId", 7L), Map.entry("realmId", REALM_ID), Map.entry("worldSlug", "demo"), From 1ac20b0e387ff085ff15dcf39dfea2fcc3607436 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 05:21:43 +1300 Subject: [PATCH 11/23] Prove Account authority linearization and isolate proxied authentication spies --- .github/workflows/ci.yml | 1 + design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 4 + ...untAuthorityGenerationIntegrationTest.java | 341 ++++++++++++++++++ ...ountAuthenticationUuidIntegrationTest.java | 20 +- 5 files changed, 365 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b6f89deed1..8dbc6bfbfa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1080,6 +1080,7 @@ jobs: --strict \ --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationIntegrationTest \ --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepositoryIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationIntegrationTest#compositeSnapshotBlocksIssuerAndTenantAdvanceAndKeepsScopeSetsIndependent()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationIntegrationTest#exhaustedAccountCountersRollbackTheWholeCallerTransaction()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepositoryIntegrationTest#exhaustedSequenceRejectsAppendWithoutChangingEventCheckpointOrCallerSentinel()' \ account-service diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 77c0f7df39..8854ac3903 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -189,3 +189,8 @@ Entry format: - Context: an Account `fullCheck` failed at `spotbugsTest` with exit code 1 but no report artifact or finding in the normal log. - Observation: rerunning the affected canonical task with `-PfullCheck --info` exposed the exact unused-method finding. The obsolete numeric assertion helper was removed and the consolidated gate rerun; no analyzer suppression or disabled check was needed. - Expected pattern: inspect the affected task's detailed output before searching for a report that its configuration does not emit, and keep the diagnostic run separate from the final consolidated proof. + +- `2026-10-02`: Stub the underlying Mockito target, not a Spring repository proxy + - Context: exact Account PostgreSQL CI36888416843 executed all14required UUID/OTP/HTTP cases but failed one setup with `UnfinishedStubbingException`; its stack crossed the persistence-exception-translation proxy while configuring `doAnswer`. + - Observation: a prior green run did not establish stable spy setup. The fixture correction unwraps the ultimate Mockito target for setup and verification, while production calls still traverse the injected Spring proxy and the real owner transaction. A separately logged scheduled-cleanup warning is not proved to cause this failure. + - Expected pattern: use `AopTestUtils.getUltimateTargetObject` when configuring a proxied spy, preserve the actual proxy on the tested call path and retain transaction/no-mutation assertions. Require executed runner proof for the corrected setup; local compilation and Docker-skipped tests cannot establish recovery. 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 53d123fb27..799959d4cc 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,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +Exact bootstrap UUID source `56a222bf289caa710285bf8655eee1d04161b22e` [CI36888416843](https://github.com/benhook1013/FireMUD/actions/runs/36888416843) executed all12Account UUID/OTP/bootstrap and2HTTP cases without skips. Thirteen passed, including the three new bootstrap UUID cases; one existing OTP case failed during Mockito setup through a Spring repository proxy, not at its persistence assertion. The corrected fixture configures and verifies ultimate Mockito targets while the tested service still uses its real injected proxies and owner transaction. A separate scheduled-cleanup warning is not established as the cause. Corrected-head runner proof remains required. + +An additional Account-local PostgreSQL case holds the exact composite generation snapshot, proves that concurrent issuer and tenant advances are blocked by that holder's exact backend, then verifies generation/source-version advancement with the independent Account fence unchanged. It also preserves membership authority when the requested tenant-authority map is empty and rejects a missing membership scope without enrollment. This is a repository linearization prerequisite, not the complete immutable evidence bundle, registry, credential producer, or cross-store authorization. Local Account check/JAR and docs passed70tasks(14executed/56up-to-date); the existing506unit results were up-to-date, not newly executed, and all159PostgreSQL cases compiled/discovered but skipped without Docker. The new method is mandatory in strict CI; executed proof is pending. Runtime RPC, credential/context, catalog and ring-mount gates remain closed. + The Account authentication producer now returns its exact persisted canonical non-nil UUID and signs that same identity in `sub`/`accountId` for password and email-OTP paths. Profile and supported self-service readers first bind the canonical UUID to the authenticated subject, then perform an Account-owned read-only provenance-checked lookup of the private numeric storage key; an unmapped UUID cannot select or mutate another row. Disabled deletion, login-factor mutation and tenant export remain denied without writes. Other numeric DTO, catalog and cross-service consumers are explicitly unfinished; this component does not establish a working end-to-end login/admission path. Game Session V9 separately adds exact command UUID storage without altering or inventing identities for retained numeric rows. The consumer-carrier correction remains a separate unpublished candidate. Local consolidated Account/Game Session full checks and JARs passed (156 tasks, 72 executed/84 up-to-date), including formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown. Account's 502 unit cases passed in the preceding same-code execution; their final task was up-to-date, not a second execution. All 149 Account PostgreSQL cases compiled/discovered and skipped without Docker, including the three new persisted-identity/profile no-mutation cases. Game Session executed 1,747 unit, 18 non-PostgreSQL integration and one cross-service case; 17 unit, 133 integration and 33 cross-service cases skipped, including five new command-storage/migration cases. The earlier possible-null integration fixture readback defect was corrected with explicit required-row checks, not an analyzer suppression. Ring publication infrastructure is an open Platform Operations prerequisite; its mount and all previously denied activation paths remain held back. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationIntegrationTest.java index de9b832c69..dfdd60ec7b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationIntegrationTest.java @@ -5,15 +5,20 @@ import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeKind; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -210,6 +215,90 @@ void explicitExactScopeStateUsesCompareAndAdvanceAndFailsClosed() throws Excepti .hasMessageContaining("malformed"); } + @Test + void compositeSnapshotBlocksIssuerAndTenantAdvanceAndKeepsScopeSetsIndependent() + throws Exception { + DatabaseFixture fixture = databaseFixture(); + DSLContext setupDsl = fixture.setupDsl(); + AccountAuthorityGenerationRepository repository = fixture.repository(); + TransactionTemplate transaction = fixture.transaction(); + + UUID accountId = insertAccount(setupDsl, "auth-comp-" + UUID.randomUUID()); + AuthorityScope issuerScope = AuthorityScope.issuer(AccountServiceImpl.ACCOUNT_JWT_ISSUER); + AuthorityScope accountScope = AuthorityScope.account(accountId); + AuthorityScope tenantScopeA = AuthorityScope.tenant(TENANT_A); + AuthorityScope tenantScopeB = AuthorityScope.tenant(TENANT_B); + AuthorityScope membershipScopeA = AuthorityScope.membership(accountId, TENANT_A); + + inTransaction(transaction, () -> repository.initializeIssuerIfAbsent(issuerScope.issuerId())); + inTransaction(transaction, () -> repository.initialize(accountScope)); + inTransaction(transaction, () -> repository.initialize(tenantScopeA)); + inTransaction(transaction, () -> repository.initialize(tenantScopeB)); + inTransaction(transaction, () -> repository.initialize(membershipScopeA)); + + CompositeSnapshot billingSafeSnapshot = + readCompositeSnapshot( + fixture, issuerScope.issuerId(), accountId, List.of(), List.of(TENANT_A)); + assertThat(billingSafeSnapshot.tenants()).isEmpty(); + assertThat(billingSafeSnapshot.memberships()) + .extracting(ScopeState::scope) + .containsExactly(membershipScopeA); + assertThat(billingSafeSnapshot.memberships().getFirst().generation()).isEqualTo(1L); + assertThat(billingSafeSnapshot.memberships().getFirst().sourceVersion()).isEqualTo(1L); + + AuthorityScope missingMembershipScope = AuthorityScope.membership(accountId, TENANT_B); + assertThat(membershipGenerationCount(setupDsl, missingMembershipScope)).isZero(); + assertThatThrownBy( + () -> + readCompositeSnapshot( + fixture, issuerScope.issuerId(), accountId, List.of(), List.of(TENANT_B))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("missing"); + assertThat(membershipGenerationCount(setupDsl, missingMembershipScope)).isZero(); + assertIssuanceFenceUnchanged(setupDsl, accountId, billingSafeSnapshot.issuanceFence()); + + CompositeSnapshot exactBaseline = + readCompositeSnapshot( + fixture, + issuerScope.issuerId(), + accountId, + List.of(TENANT_B, TENANT_A), + List.of(TENANT_A)); + CompositeSnapshot afterIssuerAdvance = + proveCompositeSnapshotBlocksAdvance(fixture, exactBaseline, exactBaseline.issuer()); + ScopeState tenantA = + afterIssuerAdvance.tenants().stream() + .filter(state -> state.scope().equals(tenantScopeA)) + .findFirst() + .orElseThrow(); + CompositeSnapshot afterTenantAdvance = + proveCompositeSnapshotBlocksAdvance(fixture, afterIssuerAdvance, tenantA); + + assertThat(afterTenantAdvance.issuer().generation()) + .isEqualTo(exactBaseline.issuer().generation() + 1L); + assertThat(afterTenantAdvance.issuer().sourceVersion()) + .isEqualTo(exactBaseline.issuer().sourceVersion() + 1L); + assertThat(afterTenantAdvance.tenants()) + .filteredOn(state -> state.scope().equals(tenantScopeA)) + .singleElement() + .satisfies( + state -> { + assertThat(state.generation()).isEqualTo(tenantA.generation() + 1L); + assertThat(state.sourceVersion()).isEqualTo(tenantA.sourceVersion() + 1L); + }); + assertThat(afterTenantAdvance.tenants()) + .filteredOn(state -> state.scope().equals(tenantScopeB)) + .containsExactly( + exactBaseline.tenants().stream() + .filter(state -> state.scope().equals(tenantScopeB)) + .findFirst() + .orElseThrow()); + assertThat(afterTenantAdvance.account()).isEqualTo(exactBaseline.account()); + assertThat(afterTenantAdvance.memberships()).isEqualTo(exactBaseline.memberships()); + assertThat(afterTenantAdvance.issuanceFence()).isEqualTo(exactBaseline.issuanceFence()); + assertIssuanceFenceUnchanged(setupDsl, accountId, exactBaseline.issuanceFence()); + } + @Test void exhaustedAccountCountersRollbackTheWholeCallerTransaction() { String schema = uniqueSchema(); @@ -472,6 +561,252 @@ private String uniqueSchema() { return SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); } + private DatabaseFixture databaseFixture() { + String schema = uniqueSchema(); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new DatabaseFixture( + setupDsl, + transactionDsl, + new AccountAuthorityGenerationRepository(transactionDsl), + new TransactionTemplate(new DataSourceTransactionManager(dataSource))); + } + + private CompositeSnapshot readCompositeSnapshot( + DatabaseFixture fixture, + String issuerId, + UUID accountId, + List tenantIds, + List membershipTenantIds) { + return inTransaction( + fixture.transaction(), + () -> + fixture + .repository() + .readCompositeSnapshot(issuerId, accountId, tenantIds, membershipTenantIds)); + } + + private CompositeSnapshot proveCompositeSnapshotBlocksAdvance( + DatabaseFixture fixture, CompositeSnapshot expectedSnapshot, ScopeState expectedAdvance) + throws Exception { + CountDownLatch snapshotHeld = new CountDownLatch(1); + CountDownLatch releaseSnapshot = new CountDownLatch(1); + CountDownLatch advanceStarted = new CountDownLatch(1); + AtomicInteger snapshotBackendPid = new AtomicInteger(-1); + AtomicInteger advanceBackendPid = new AtomicInteger(-1); + AtomicReference heldSnapshot = new AtomicReference<>(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + var snapshotTransaction = + executor.submit( + () -> + inTransaction( + fixture.transaction(), + () -> { + CompositeSnapshot snapshot = + fixture + .repository() + .readCompositeSnapshot( + expectedSnapshot.issuer().scope().issuerId(), + expectedSnapshot.account().scope().accountId(), + expectedSnapshot.tenants().stream() + .map(state -> state.scope().tenantId()) + .toList(), + expectedSnapshot.memberships().stream() + .map(state -> state.scope().tenantId()) + .toList()); + heldSnapshot.set(snapshot); + Integer backendPid = + fixture + .transactionDsl() + .resultQuery("SELECT pg_backend_pid()") + .fetchOne(0, Integer.class); + snapshotBackendPid.set( + Objects.requireNonNull( + backendPid, "Expected PostgreSQL backend for held snapshot")); + snapshotHeld.countDown(); + awaitBounded(releaseSnapshot); + return snapshot; + })); + + assertThat(snapshotHeld.await(20, TimeUnit.SECONDS)).isTrue(); + assertThat(heldSnapshot.get()).isEqualTo(expectedSnapshot); + + var advanceTransaction = + executor.submit( + () -> + inTransaction( + fixture.transaction(), + () -> { + Integer backendPid = + fixture + .transactionDsl() + .resultQuery("SELECT pg_backend_pid()") + .fetchOne(0, Integer.class); + advanceBackendPid.set( + Objects.requireNonNull( + backendPid, "Expected PostgreSQL backend for authority advance")); + advanceStarted.countDown(); + return fixture + .repository() + .advance(expectedAdvance, expectedAdvance.issuanceFence()); + })); + + assertThat(advanceStarted.await(20, TimeUnit.SECONDS)).isTrue(); + int snapshotPid = snapshotBackendPid.get(); + int backendPid = advanceBackendPid.get(); + awaitBlockedByBackend(fixture.setupDsl(), snapshotPid, backendPid); + assertThat(advanceTransaction.isDone()).isFalse(); + assertPersistedGeneration(fixture.setupDsl(), expectedAdvance); + assertIssuanceFenceUnchanged( + fixture.setupDsl(), + expectedSnapshot.account().scope().accountId(), + expectedSnapshot.issuanceFence()); + + releaseSnapshot.countDown(); + CompositeSnapshot completedHeldSnapshot = snapshotTransaction.get(20, TimeUnit.SECONDS); + ScopeState advanced = advanceTransaction.get(20, TimeUnit.SECONDS); + assertThat(completedHeldSnapshot).isEqualTo(expectedSnapshot); + assertThat(advanced.generation()).isEqualTo(expectedAdvance.generation() + 1L); + assertThat(advanced.sourceVersion()).isEqualTo(expectedAdvance.sourceVersion() + 1L); + assertThat(advanced.issuanceFence()).isNull(); + assertPersistedGeneration(fixture.setupDsl(), advanced); + + CompositeSnapshot afterRelease = + readCompositeSnapshot( + fixture, + expectedSnapshot.issuer().scope().issuerId(), + expectedSnapshot.account().scope().accountId(), + expectedSnapshot.tenants().stream().map(state -> state.scope().tenantId()).toList(), + expectedSnapshot.memberships().stream() + .map(state -> state.scope().tenantId()) + .toList()); + ScopeState expectedIssuer = + expectedAdvance.scope().kind() == ScopeKind.ISSUER ? advanced : expectedSnapshot.issuer(); + List expectedTenants = + expectedSnapshot.tenants().stream() + .map(state -> state.scope().equals(expectedAdvance.scope()) ? advanced : state) + .toList(); + assertThat(afterRelease.issuer()).isEqualTo(expectedIssuer); + assertThat(afterRelease.account()).isEqualTo(expectedSnapshot.account()); + assertThat(afterRelease.tenants()).containsExactlyElementsOf(expectedTenants); + assertThat(afterRelease.memberships()).isEqualTo(expectedSnapshot.memberships()); + assertThat(afterRelease.issuanceFence()).isEqualTo(expectedSnapshot.issuanceFence()); + assertIssuanceFenceUnchanged( + fixture.setupDsl(), + expectedSnapshot.account().scope().accountId(), + expectedSnapshot.issuanceFence()); + return afterRelease; + } finally { + releaseSnapshot.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + + private void awaitBlockedByBackend( + DSLContext setupDsl, int snapshotBackendPid, int advanceBackendPid) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(20); + while (System.nanoTime() < deadline) { + Boolean blockedBySnapshot = + setupDsl + .resultQuery( + "SELECT ? = ANY(pg_blocking_pids(?))", snapshotBackendPid, advanceBackendPid) + .fetchOne(0, Boolean.class); + if (Boolean.TRUE.equals(blockedBySnapshot)) { + return; + } + Thread.sleep(10L); + } + throw new AssertionError( + "Authority advance was not blocked by held composite snapshot backend " + + snapshotBackendPid + + "; advance backend: " + + advanceBackendPid); + } + + private void assertPersistedGeneration(DSLContext setupDsl, ScopeState expected) { + var row = + Objects.requireNonNull( + setupDsl + .resultQuery( + "SELECT generation, source_version FROM account_authority_generations " + + "WHERE scope_kind = ? AND issuer_id IS NOT DISTINCT FROM ? " + + "AND account_uuid IS NOT DISTINCT FROM ? " + + "AND tenant_uuid IS NOT DISTINCT FROM ?", + expected.scope().kind().name(), + expected.scope().issuerId(), + expected.scope().accountId(), + expected.scope().tenantId()) + .fetchOne(), + "Expected persisted authority-generation row for " + expected.scope()); + assertThat(row.get("generation", Long.class)).isEqualTo(expected.generation()); + assertThat(row.get("source_version", Long.class)).isEqualTo(expected.sourceVersion()); + } + + private void assertIssuanceFenceUnchanged( + DSLContext setupDsl, UUID accountId, IssuanceFence expected) { + Long persistedFence = + Objects.requireNonNull( + setupDsl + .resultQuery( + "SELECT issuance_fence FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + accountId) + .fetchOne(0, Long.class), + "Expected persisted Account issuance fence"); + Long persistedSourceVersion = + Objects.requireNonNull( + setupDsl + .resultQuery( + "SELECT source_version FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + accountId) + .fetchOne(0, Long.class), + "Expected persisted Account issuance-fence source version"); + assertThat(persistedFence).isEqualTo(expected.value()); + assertThat(persistedSourceVersion).isEqualTo(expected.sourceVersion()); + } + + private Long membershipGenerationCount(DSLContext setupDsl, AuthorityScope membershipScope) { + return Objects.requireNonNull( + setupDsl + .resultQuery( + "SELECT count(*) FROM account_authority_generations " + + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? AND tenant_uuid = ?", + membershipScope.accountId(), + membershipScope.tenantId()) + .fetchOne(0, Long.class), + "Expected membership-generation row count"); + } + + private void awaitBounded(CountDownLatch latch) { + try { + if (!latch.await(30, TimeUnit.SECONDS)) { + throw new IllegalStateException("Composite authority snapshot release was not signaled"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Composite authority snapshot was interrupted", interrupted); + } + } + private void proveConcurrentStaleMembershipAdvance( AccountAuthorityGenerationRepository repository, TransactionTemplate transaction, @@ -589,4 +924,10 @@ private enum OverflowCounter { ISSUANCE_FENCE, ISSUANCE_FENCE_SOURCE_VERSION } + + private record DatabaseFixture( + DSLContext setupDsl, + DSLContext transactionDsl, + AccountAuthorityGenerationRepository repository, + TransactionTemplate transaction) {} } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java index b21cafba3f..736cc8b418 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java @@ -46,6 +46,7 @@ import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.test.util.AopTestUtils; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; @@ -106,13 +107,15 @@ static void configure(DynamicPropertyRegistry registry) { void cleanDatabaseAndObserveOwnerTransaction() { dsl.execute("TRUNCATE TABLE account_audit_outbox"); dsl.execute("TRUNCATE TABLE accounts RESTART IDENTITY CASCADE"); + AccountEmailLoginChallengeRepository challengeRepositoryTarget = + AopTestUtils.getUltimateTargetObject(challengeRepositorySpy); doAnswer( invocation -> { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); invocation.callRealMethod(); return null; }) - .when(challengeRepositorySpy) + .when(challengeRepositoryTarget) .lockAccountChallenge(anyLong()); } @@ -242,7 +245,7 @@ void playerBootstrapEmailOtpCarriesPersistedUuidAndConsumesChallengeExactlyOnce( assertThat(emailLoginChallengeCount(persisted.getId())).isZero(); assertThat(sessionService.isAccountSessionActive(persisted.getId(), result.bootstrapToken())) .isTrue(); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.times(1)) + org.mockito.Mockito.verify(sessionServiceTarget(), org.mockito.Mockito.times(1)) .storeAccountSession( org.mockito.ArgumentMatchers.eq(persisted.getId()), org.mockito.ArgumentMatchers.eq(result.bootstrapToken()), @@ -261,7 +264,7 @@ void bootstrapConsumerRejectsUnmappedAccountUuidBeforeSessionLookup() { .isInstanceOf(AuthenticationException.class) .hasMessage("Invalid bootstrap token"); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + org.mockito.Mockito.verify(sessionServiceTarget(), org.mockito.Mockito.never()) .isAccountSessionActive(anyLong(), org.mockito.ArgumentMatchers.anyString()); } @@ -356,7 +359,7 @@ private void assertRejectedEmailOtpPersistsChallengeAttempt( assertThat(accountUuidFor(persisted.getId())).isEqualTo(persisted.getAccountUuid()); assertThat(accountService.resolveAccountStorageId(persisted.getAccountUuid())) .isEqualTo(persisted.getId()); - org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + org.mockito.Mockito.verify(sessionServiceTarget(), org.mockito.Mockito.never()) .storeAccountSession( org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString(), @@ -369,11 +372,12 @@ void nonAuthenticationSessionFailureRollsBackOtpConsumption() { String deliveredCode = requestEmailLoginOtpAndCaptureCode(persisted.getEmail()); var challengeBeforeFailure = challengeRepositorySpy.findByAccountId(persisted.getId()).orElseThrow(); + SessionService sessionServiceTarget = sessionServiceTarget(); doAnswer( invocation -> { throw new IllegalStateException("simulated session storage failure"); }) - .when(sessionService) + .when(sessionServiceTarget) .storeAccountSession( org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString(), @@ -385,7 +389,7 @@ void nonAuthenticationSessionFailureRollsBackOtpConsumption() { .hasMessage("simulated session storage failure"); ArgumentCaptor tokenCaptor = ArgumentCaptor.forClass(String.class); - org.mockito.Mockito.verify(sessionService) + org.mockito.Mockito.verify(sessionServiceTarget) .storeAccountSession( org.mockito.ArgumentMatchers.anyLong(), tokenCaptor.capture(), @@ -543,4 +547,8 @@ private static String hashPassword(String password) { argon2.wipeArray(chars); } } + + private SessionService sessionServiceTarget() { + return AopTestUtils.getUltimateTargetObject(sessionService); + } } From 91c062f6b43159ee57a3d53c82e940014728047f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 05:42:59 +1300 Subject: [PATCH 12/23] Expose proved canonical Account UUIDs in registration and local export --- .../account-service/api-contracts.md | 4 +- .../player-access-and-session.md | 2 + protos/account/v1/account_service.proto | 2 +- .../accountservice/dto/AccountDto.java | 2 +- .../accountservice/mapper/AccountMapper.java | 4 +- .../service/impl/AccountGrpcService.java | 2 +- .../service/impl/AccountServiceImpl.java | 3 +- .../src/main/resources/openapi.yaml | 4 +- ...ountAuthenticationUuidIntegrationTest.java | 43 ++++++++++++++----- .../controller/AccountControllerTest.java | 8 ++-- .../PublicBootstrapRoutesProdProfileTest.java | 5 ++- .../service/impl/AccountGrpcServiceTest.java | 6 ++- .../service/impl/AccountServiceImplTest.java | 37 ++++++++++++++-- 13 files changed, 92 insertions(+), 30 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index b74ba623c4..7e0cc38129 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -60,13 +60,13 @@ The hosted Creator Party, terms catalog, acceptance/currentness evidence, and ch The current credential-granting `Authenticate`, `RequestEmailLoginOtp`, and `VerifyEmailLoginOtp` gRPC handlers require the exact authenticated Game Session mTLS peer before credential or challenge work; the shared public-method list still bypasses bearer validation for these methods, so the peer guard is required and is not a JWT fallback. Legacy profile GET/PUT now require the exact Social Groups peer and a non-internal caller subject matching the requested account; presence-policy batch reads require the exact Social Groups peer and read only tenant-scoped profiles. The account-ID export, external-link, and verification gRPC handlers deny before data access or mutation because no authorized caller contract exists. Runtime membership, grant, and entitlement methods deny before Account reads until typed player/target binding is available; these local guards are not complete admission proof. `GetBalance`, `AddCurrency`, and `SpendCurrency` now return `FAILED_PRECONDITION` before balance access or mutation because virtual currency is a deferred substrate, not a supported v1 API. -The authentication response's `accountId` is the canonical non-nil UUID required by [Identifier Glossary](../../system-architecture-identifier-glossary.md); Account must prove the exact persisted `account_uuid`, recognized provenance and unchanged numeric source row before issuing the result or consuming a successful challenge. `Authenticate`, email-OTP completion, REST `/auth/login` and `/auth/player-bootstrap` carry that same UUID, and each token's subject and Account identity claim carry it under the [JWT owner](../../system-architecture-jwt-and-token-contracts.md). Account's client-readable bootstrap connect-scope token also binds that exact Account UUID; its owner-local reader validates the subject/claim match and source readback before recovering any private storage selector. The numeric Account primary key remains an Account-local storage selector, never an alternate wire identity. A missing or contradictory source denies credential creation; no tenant association or admission follows from proving global Account identity. Numeric tenant/catalog and other cross-owner consumers, complete token registry and activation proof remain separately tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). +Registration's `AccountDto.id` and `CreateAccount.accountId`, together with the authentication response's `accountId`, carry the exact persisted canonical non-nil UUID required by [Identifier Glossary](../../system-architecture-identifier-glossary.md); Account must prove the exact persisted `account_uuid`, recognized provenance and unchanged numeric source row before issuing the result or consuming a successful challenge. `Authenticate`, email-OTP completion, REST `/auth/login` and `/auth/player-bootstrap` carry that same UUID, and each token's subject and Account identity claim carry it under the [JWT owner](../../system-architecture-jwt-and-token-contracts.md). Account's client-readable bootstrap connect-scope token also binds that exact Account UUID; its owner-local reader validates the subject/claim match and source readback before recovering any private storage selector. The numeric Account primary key remains an Account-local storage selector, never an alternate wire identity. A missing or contradictory source denies credential creation; no tenant association or admission follows from proving global Account identity. Numeric tenant/catalog and other cross-owner consumers, complete token registry and activation proof remain separately tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). Fresh-tenant identity adds no public Account endpoint or membership shortcut. The #2915 consumer uses Account's authenticated normal workload to read exact Game Design creation evidence, then commits an immutable canonical-UUID association and shared UUID conflict claim before using the existing no-reset tenant-generation initialization; it neither infers a retained numeric key nor admits a player. Exact #2915 head `910d0a6f41d60ee7214b610d56f89c51db260413` [CI 36796087279](https://github.com/benhook1013/FireMUD/actions/runs/36796087279) executed and passed all six Account fresh-association and seven Game Design creation PostgreSQL cases without skips, including retry, concurrency and rollback. This corrected component proof supersedes the earlier schema-fixture failure; it does not prove deployed workload identity, a live cross-owner handoff or activation. Detailed proof and remaining gates belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). The Game Design wire and digest remain owned by its [API contract](../game-design-service/api-contracts.md#fresh-tenant-creation-operation-and-account-readback), and Account's local storage/readback consequence is described in [Runtime & Data](./runtime-and-data.md). The membership RPC remains denied. `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. -The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` is Account/profile-local, while direct account-ID `ExportAccount` gRPC denies before reading; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the account-targeted gRPC and legacy REST tenant-export now deny before reading global Account fields; neither implements that target. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration now creates only global Account state and its platform audit outbox row; it does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. A bounded Account-owned readback worker revisits abandoned PENDING intents and can terminalize only an exact proved JOIN operation, membership, and audit envelope; expiry or missing evidence leaves the intent nonterminal with attempt diagnostics. PostgreSQL runtime proof for lost-acknowledgement, concurrent retry/reconciler, unresolved evidence, and direct text end-to-end behavior remains open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Fresh connect-token issuance treats `INACTIVE` membership as nonadmitting and fails closed for non-public targets until lifecycle-qualified, expiring grant authority is available; it also lacks an atomic membership-version/authority-generation commit gate. Text `PLAY` locally checks lifecycle consistency and a positive membership authority generation on mocked Account responses, but complete authenticated same-snapshot evidence is absent and live Account gRPC reads deny before data access; its conditional entitlement/public-policy order is unit-tested only. Current non-public or non-visible target handling remains split across discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. +The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` is Account/profile-local, while direct account-ID `ExportAccount` gRPC denies before reading; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the account-targeted gRPC and legacy REST tenant-export now deny before reading global Account fields; neither implements that target. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Public registration now creates only global Account state and its platform audit outbox row; it does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. A bounded Account-owned readback worker revisits abandoned PENDING intents and can terminalize only an exact proved JOIN operation, membership, and audit envelope; expiry or missing evidence leaves the intent nonterminal with attempt diagnostics. PostgreSQL runtime proof for lost-acknowledgement, concurrent retry/reconciler, unresolved evidence, and direct text end-to-end behavior remains open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Fresh connect-token issuance treats `INACTIVE` membership as nonadmitting and fails closed for non-public targets until lifecycle-qualified, expiring grant authority is available; it also lacks an atomic membership-version/authority-generation commit gate. Text `PLAY` locally checks lifecycle consistency and a positive membership authority generation on mocked Account responses, but complete authenticated same-snapshot evidence is absent and live Account gRPC reads deny before data access; its conditional entitlement/public-policy order is unit-tested only. Current non-public or non-visible target handling remains split across discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Other profile/tenant DTOs and their OpenAPI fields still retain numeric identifiers; registration, `AccountDto.id`, and auth/bootstrap carry the proved canonical Account UUID. Migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. ### Current JOIN Readback Behavior 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 799959d4cc..96a59d9013 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 +Registration and the Account component of the local export now emit the exact persisted canonical UUID as `AccountDto.id`; `CreateAccount` returns it unchanged, and new `ACCOUNT_REGISTERED` platform audit payloads bind that same UUID. The private numeric row key remains only an Account-owned storage selector. The unused reverse DTO-to-entity mapper is removed; no UUID-to-numeric compatibility path is added and retained audit history is not rewritten. Export verifies UUID/provenance/source-row readback before profile reads, with unmapped and contradictory identity denial tests. Profile and tenant DTO identities remain open migration work. The affected full Account check/JAR and docs passed70tasks(42executed/28up-to-date);508unit cases executed without failures/errors/skips, while all159PostgreSQL cases compiled/discovered but skipped without Docker. Updated registration UUID/private-row and exact durable-audit assertions still require corrected-head runner execution. No credential, membership RPC, catalog or ring mount is enabled. + Exact bootstrap UUID source `56a222bf289caa710285bf8655eee1d04161b22e` [CI36888416843](https://github.com/benhook1013/FireMUD/actions/runs/36888416843) executed all12Account UUID/OTP/bootstrap and2HTTP cases without skips. Thirteen passed, including the three new bootstrap UUID cases; one existing OTP case failed during Mockito setup through a Spring repository proxy, not at its persistence assertion. The corrected fixture configures and verifies ultimate Mockito targets while the tested service still uses its real injected proxies and owner transaction. A separate scheduled-cleanup warning is not established as the cause. Corrected-head runner proof remains required. An additional Account-local PostgreSQL case holds the exact composite generation snapshot, proves that concurrent issuer and tenant advances are blocked by that holder's exact backend, then verifies generation/source-version advancement with the independent Account fence unchanged. It also preserves membership authority when the requested tenant-authority map is empty and rejects a missing membership scope without enrollment. This is a repository linearization prerequisite, not the complete immutable evidence bundle, registry, credential producer, or cross-store authorization. Local Account check/JAR and docs passed70tasks(14executed/56up-to-date); the existing506unit results were up-to-date, not newly executed, and all159PostgreSQL cases compiled/discovered but skipped without Docker. The new method is mandatory in strict CI; executed proof is pending. Runtime RPC, credential/context, catalog and ring-mount gates remain closed. diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 8de04ec592..85a725081f 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -97,7 +97,7 @@ message CreateAccountRequest { // Result of a CreateAccount call. message CreateAccountResponse { - // Unique identifier of the newly created account. + // Canonical non-nil Account UUID of the newly created account. string account_id = 1; // Details about why the creation failed, if applicable. shared.v1.ErrorDetail error = 2; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java index ed43a78720..3636796911 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java @@ -5,7 +5,7 @@ import jakarta.validation.constraints.Size; public record AccountDto( - Long id, + String id, @NotNull @Size(max = 50) String username, @NotNull @Email @Size(max = 100) String email, @Size(max = 20) String role, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java index 0b3fb0906b..64fc62b49a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java @@ -3,11 +3,11 @@ import net.firedevops.firemud.accountservice.dto.AccountDto; import net.firedevops.firemud.accountservice.entity.Account; import org.mapstruct.Mapper; +import org.mapstruct.Mapping; import org.mapstruct.ReportingPolicy; @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) public interface AccountMapper { + @Mapping(target = "id", source = "accountUuid") AccountDto toDto(Account entity); - - Account toEntity(AccountDto dto); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index b17187ccac..ee731fe806 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -305,7 +305,7 @@ public void createAccount( request.getUsername(), request.getEmail(), request.getPassword()); var account = accountService.createAccount(dto); CreateAccountResponse response = - CreateAccountResponse.newBuilder().setAccountId(account.id().toString()).build(); + CreateAccountResponse.newBuilder().setAccountId(account.id()).build(); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (AccountAlreadyExistsException ex) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 5bf6aa60dc..07d20ef961 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -253,7 +253,7 @@ public AccountDto createAccount(CreateAccountRequest request) { "platform", null, "ACCOUNT_REGISTERED", - "{\"accountId\":" + saved.getId() + "}"); + "{\"accountId\":\"" + saved.getAccountUuid() + "\"}"); return accountMapper.toDto(saved); } @@ -2139,6 +2139,7 @@ public AccountLoginAuthModesDto updateLoginAuthModes( @Timed(value = "account.export") public AccountDataExportDto exportAccountData(Long accountId) { Account account = requireAccount(accountId); + requirePersistedAccountUuid(account); List profiles = profileRepository.findByAccountId(accountId).stream().map(profileMapper::toDto).toList(); return new AccountDataExportDto(accountMapper.toDto(account), profiles); diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index ab4a946695..de8271449a 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -36,7 +36,9 @@ components: type: object properties: id: - type: integer + type: string + format: uuid + description: Canonical non-nil Account UUID; never the numeric database primary key. username: type: string email: diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java index 736cc8b418..12c314f744 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java @@ -130,13 +130,34 @@ void repositoryInsertAuthenticationUsesExactPersistedUuidAndPrivateStorageKey() String username = "repo-" + suffix; String email = username + "@example.com"; var created = accountService.createAccount(new CreateAccountRequest(username, email, PASSWORD)); - Account persisted = accountRepository.findById(created.id()).orElseThrow(); + UUID returnedAccountUuid = UUID.fromString(created.id()); + long accountId = accountService.resolveAccountStorageId(returnedAccountUuid); + Account persisted = accountRepository.findById(accountId).orElseThrow(); + + assertThat(created.id()) + .isEqualTo(persisted.getAccountUuid().toString()) + .isNotEqualTo(Long.toString(accountId)); assertThat(persisted.getAccountUuidProvenance()) .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); - assertThat(persisted.getAccountUuidSourceNumericId()).isEqualTo(created.id()); + assertThat(persisted.getAccountUuidSourceNumericId()).isEqualTo(accountId); + assertThat(accountService.resolveAccountStorageId(returnedAccountUuid)).isEqualTo(accountId); + var registrationAudit = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT payload FROM account_audit_outbox " + + "WHERE scope = 'platform' AND tenant_id IS NULL " + + "AND producer_service = 'account-service' " + + "AND event_type = 'ACCOUNT_REGISTERED'") + .fetchOne(), + "Expected durable ACCOUNT_REGISTERED platform audit row"); + String registrationAuditPayload = + Objects.requireNonNull( + registrationAudit.get(0, String.class), "Expected registration audit payload"); + assertThat(registrationAuditPayload) + .isEqualTo("{\"accountId\":\"" + returnedAccountUuid + "\"}"); - assertAuthenticationAndPrivateLookup(username, created.id(), persisted.getAccountUuid()); + assertAuthenticationAndPrivateLookup(username, accountId, persisted.getAccountUuid()); } @Test @@ -408,20 +429,21 @@ void unmappedUuidDeniesProfileMutationEvenWhenBodyNamesAnExistingPrivateRow() { String username = "profile-" + suffix; String email = username + "@example.com"; var created = accountService.createAccount(new CreateAccountRequest(username, email, PASSWORD)); + long accountId = accountService.resolveAccountStorageId(UUID.fromString(created.id())); dsl.execute( "INSERT INTO account_tenant_membership " + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + "membership_version, membership_authority_generation, authority_provenance) " + "VALUES (?, ?, TRUE, 'ACTIVE', 1, 1, 'EXPLICIT_JOIN')", - created.id(), + accountId, PROFILE_TENANT_ID); dsl.execute( "INSERT INTO profiles (account_id, tenant_id, display_name, bio) VALUES (?, ?, ?, ?)", - created.id(), + accountId, PROFILE_TENANT_ID, "original-display-name", "original-bio"); - String profileBefore = profileRowJson(created.id()); + String profileBefore = profileRowJson(accountId); UUID unmappedUuid = UUID.randomUUID(); String testToken = @@ -434,7 +456,7 @@ void unmappedUuidDeniesProfileMutationEvenWhenBodyNamesAnExistingPrivateRow() { UpdateProfileRequest request = new UpdateProfileRequest( PROFILE_TENANT_ID, - created.id(), + accountId, "must-not-be-written", "must-not-be-written", ProfilePresenceVisibilityPolicy.PRIVATE); @@ -443,7 +465,7 @@ void unmappedUuidDeniesProfileMutationEvenWhenBodyNamesAnExistingPrivateRow() { .isInstanceOf(IllegalArgumentException.class) .hasMessage("Account not found"); - assertThat(profileRowJson(created.id())).isEqualTo(profileBefore); + assertThat(profileRowJson(accountId)).isEqualTo(profileBefore); } private void assertAuthenticationAndPrivateLookup( @@ -491,9 +513,10 @@ private Account createVerifiedAccount(String prefix) { String username = prefix + "-" + UUID.randomUUID(); String email = username + "@example.com"; var created = accountService.createAccount(new CreateAccountRequest(username, email, PASSWORD)); - assertThat(dsl.execute("UPDATE accounts SET email_verified = TRUE WHERE id = ?", created.id())) + long accountId = accountService.resolveAccountStorageId(UUID.fromString(created.id())); + assertThat(dsl.execute("UPDATE accounts SET email_verified = TRUE WHERE id = ?", accountId)) .isEqualTo(1); - return accountRepository.findById(created.id()).orElseThrow(); + return accountRepository.findById(accountId).orElseThrow(); } private String requestEmailLoginOtpAndCaptureCode(String email) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java index 477723f3b7..517d3b7766 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java @@ -67,7 +67,7 @@ void clear() { @Test void createAccountReturnsDto() throws Exception { CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "password"); - AccountDto response = new AccountDto(1L, "demo", "demo@example.com", "player", true); + AccountDto response = new AccountDto(ACCOUNT_UUID, "demo", "demo@example.com", "player", true); when(accountService.createAccount(request)).thenReturn(response); mockMvc @@ -77,6 +77,7 @@ void createAccountReturnsDto() throws Exception { .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) + .andExpect(jsonPath("$.data.id").value(ACCOUNT_UUID)) .andExpect(jsonPath("$.data.username").value("demo")); } @@ -141,7 +142,7 @@ void deleteAccountRejectsScopedTenantAdminBecauseFullDeletionIsAccountScoped() t @Test void exportAccountAllowsCurrentAccountWithoutTenantScope() throws Exception { - AccountDto account = new AccountDto(42L, "demo", "demo@example.com", "player", true); + AccountDto account = new AccountDto(ACCOUNT_UUID, "demo", "demo@example.com", "player", true); when(accountService.exportAccountData(42L)) .thenReturn(new AccountDataExportDto(account, List.of())); when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))).thenReturn(42L); @@ -152,7 +153,8 @@ void exportAccountAllowsCurrentAccountWithoutTenantScope() throws Exception { get("/accounts/" + ACCOUNT_UUID + "/export") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) - .andExpect(jsonPath("$.status").value("SUCCESS")); + .andExpect(jsonPath("$.status").value("SUCCESS")) + .andExpect(jsonPath("$.data.account.id").value(ACCOUNT_UUID)); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java index 2df18b7b4c..0e832fcd2d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java @@ -28,6 +28,7 @@ @Import({CommonSecurityAutoConfiguration.class, CommonSecurityServletAutoConfiguration.class}) @WithFiremudHttpAuthTestProperties class PublicBootstrapRoutesProdProfileTest { + private static final String ACCOUNT_UUID = "550e8400-e29b-41d4-a716-446655440000"; @Autowired private MockMvc mockMvc; @MockitoBean private AccountService accountService; @@ -59,7 +60,7 @@ void accountCreationRemainsPublicInProdProfile() throws Exception { CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "swordfish"); when(accountService.createAccount(request)) - .thenReturn(new AccountDto(1L, "demo", "demo@example.com", "player", true)); + .thenReturn(new AccountDto(ACCOUNT_UUID, "demo", "demo@example.com", "player", true)); mockMvc .perform( @@ -68,7 +69,7 @@ void accountCreationRemainsPublicInProdProfile() throws Exception { .content(objectMapper.writeValueAsString(request))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")) - .andExpect(jsonPath("$.data.id").value(1)) + .andExpect(jsonPath("$.data.id").value(ACCOUNT_UUID)) .andExpect(jsonPath("$.data.username").value("demo")); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index e5120fab7f..2dbf6d1c63 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -797,7 +797,9 @@ void createAccountReturnsAccountIdForGlobalRequest() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.createAccount(Mockito.any())) - .thenReturn(new AccountDto(1L, "demo", "e@example.com", "player", true)); + .thenReturn( + new AccountDto( + "550e8400-e29b-41d4-a716-446655440000", "demo", "e@example.com", "player", true)); AccountGrpcService service = new AccountGrpcService(pingService, accountService); AtomicReference ref = new AtomicReference<>(); @@ -821,7 +823,7 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("1", ref.get().getAccountId()); + assertEquals("550e8400-e29b-41d4-a716-446655440000", ref.get().getAccountId()); org.mockito.ArgumentCaptor captor = org.mockito.ArgumentCaptor.forClass( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index a65b218357..4cade89bb7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -285,7 +285,7 @@ void createAccountPersistsOnlyGlobalIdentity() { AccountDto dto = service.createAccount(request); - assertEquals(1L, dto.id()); + assertEquals(accountUuid.toString(), dto.id()); assertEquals("demo", dto.username()); org.mockito.ArgumentCaptor accountCaptor = org.mockito.ArgumentCaptor.forClass(Account.class); @@ -299,7 +299,7 @@ void createAccountPersistsOnlyGlobalIdentity() { org.mockito.ArgumentMatchers.eq("platform"), org.mockito.ArgumentMatchers.isNull(), org.mockito.ArgumentMatchers.eq("ACCOUNT_REGISTERED"), - org.mockito.ArgumentMatchers.eq("{\"accountId\":1}")); + org.mockito.ArgumentMatchers.eq("{\"accountId\":\"" + accountUuid + "\"}")); assertEquals(null, accountCaptor.getValue().getRole()); verifyNoInteractions(profileRepository, accountTenantMembershipRepository); } @@ -335,7 +335,7 @@ void createAccountInitializesCanonicalAccountAuthorityBeforeRegistrationAudit() org.mockito.ArgumentMatchers.eq("platform"), org.mockito.ArgumentMatchers.isNull(), org.mockito.ArgumentMatchers.eq("ACCOUNT_REGISTERED"), - org.mockito.ArgumentMatchers.eq("{\"accountId\":1}")); + org.mockito.ArgumentMatchers.eq("{\"accountId\":\"" + accountUuid + "\"}")); } @Test @@ -5110,8 +5110,10 @@ void updateProfileRejectsReservedHiddenStaffPolicyBeforePersistence() { void exportAccountDataIncludesProfilesAcrossTenants() { Account account = new Account(); account.setId(2L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setEmail("demo@example.com"); + UUID accountUuid = account.getAccountUuid(); Profile tenantOne = profile(account, 1L, "one"); Profile tenantTwo = profile(account, 2L, "two"); when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); @@ -5127,10 +5129,37 @@ void exportAccountDataIncludesProfilesAcrossTenants() { var export = service.exportAccountData(2L); - assertEquals(2L, export.account().id()); + assertEquals(accountUuid.toString(), export.account().id()); assertEquals(2, export.profiles().size()); } + @Test + void exportAccountDataRejectsContradictoryIdentityBeforeReadingProfiles() { + Account account = new Account(); + account.setId(2L); + setPersistedAuthenticationIdentity(account); + account.setAccountUuidSourceNumericId(3L); + when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); + + assertThrows(IllegalStateException.class, () -> service.exportAccountData(2L)); + + verifyNoInteractions(profileRepository, profileMapper); + } + + @Test + void exportAccountDataRejectsUnmappedIdentityBeforeReadingProfiles() { + Account account = new Account(); + account.setId(2L); + setPersistedAuthenticationIdentity(account); + when(accountRepository.findById(2L)).thenReturn(Optional.of(account)); + when(accountRepository.findByAccountUuid(account.getAccountUuid())) + .thenReturn(Optional.empty()); + + assertThrows(IllegalArgumentException.class, () -> service.exportAccountData(2L)); + + verifyNoInteractions(profileRepository, profileMapper); + } + @Test void exportTenantDataFailsClosedBeforeReadingAccountOrTenantData() { org.springframework.web.server.ResponseStatusException exception = From b93efaedbaec8a36294a594a946a010641e345b4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 06:31:12 +1300 Subject: [PATCH 13/23] Require explicit runtime membership authority availability and correct UUID audit proof --- .github/workflows/ci.yml | 2 + .../account-service/runtime-and-data.md | 2 +- design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 6 + protos/account/v1/account_service.proto | 1 + .../service/impl/AccountGrpcService.java | 1 + .../AccountApplicationIntegrationTest.java | 9 +- .../service/impl/AccountGrpcServiceTest.java | 3 + .../test/AccountRuntimeStubServer.java | 1 + .../command/text/PlayCommandHandler.java | 3 +- .../command/text/PlayCommandHandlerTest.java | 111 ++++++++++++++++++ .../stubs/WorldManagementStubServerTest.java | 16 +-- .../RuntimeMembershipTestFixtures.java | 1 + 13 files changed, 148 insertions(+), 13 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8dbc6bfbfa..efa5fbb068 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -993,6 +993,7 @@ jobs: run: | ./gradlew :account-service:integrationTest \ --tests net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest \ + --tests net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest.publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly \ --tests net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest.exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope \ --tests net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest.updateProfileRejectsZeroTenantIdWithInvalidArgumentEnvelope \ -PfullCheck --no-build-cache --no-configuration-cache @@ -1014,6 +1015,7 @@ jobs: --require-case 'net.firedevops.firemud.accountservice.service.AccountAuthenticationUuidIntegrationTest#nonAuthenticationSessionFailureRollsBackOtpConsumption()' \ --require-case 'net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest#exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope()' \ --require-case 'net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest#updateProfileRejectsZeroTenantIdWithInvalidArgumentEnvelope()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest#publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly()' \ account-service - name: Run Game Session command Account UUID storage PostgreSQL component proof diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index c59ca9af9f..0ff96140e4 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -195,7 +195,7 @@ Runtime caller contract: - Minimum request fields: `accountId`, `tenantId`, `requestId`. - Target minimum response fields: `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `authorityAvailability`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and the applicable `outboxCheckpoints[]` entry for the membership authority stream. - `membershipAuthorityGeneration` is an opaque Account-owned value. Runtime callers compare it only for exact freshness/equality and must not infer ordering or authority from its representation. It is the authoritative generation for connect-token issuance, gameplay-token refresh, gameplay binding and reconnect validation, and membership revocation. -- `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before its snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The current candidate proto and Account encoder carry lifecycle, roles, the exact one-tenant version map, the authority tuple, issuance fence, checkpoints, and separate source-event evidence. Game Session's candidate validates their correspondence and denies unsupported advanced upstream authority rather than resetting its checkpoints. The candidate does not yet carry explicit `authorityAvailability`, and its request selectors still use retained numeric identities. The live Account RPC rejects before data access; neither mocked responses nor the disabled encoder establish a live Account-authenticated snapshot, a fresh-UUID request handoff, or admission. Detailed implementation and proof limits belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). +- `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before its snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The held-back candidate carries that explicit availability, lifecycle, roles, the exact one-tenant version map, the authority tuple, issuance fence, checkpoints, and separate source-event evidence. Request identities and exact response echoes use canonical Account/tenant UUIDs rather than private retained numeric selectors. Game Session validates their correspondence and denies absent, unknown or unavailable availability and unsupported advanced upstream authority rather than resetting checkpoints. The live Account RPC rejects before data access; neither mocked responses nor the disabled encoder establish a live Account-authenticated snapshot, fresh-UUID handoff, or admission. Detailed implementation and proof limits belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). - `GetTenantEntitlementsForRuntime(tenantId, requestId)` is the authoritative internal entitlement surface for gameplay/runtime flows. Runtime callers may cache its positive result only under the strict-new-commitment and bounded-continuity rules in [ADR 0028](../../decisions/adr-0028-differentiated-entitlement-freshness.md); the cache never becomes a second writer. - Minimum request fields: `tenantId`, `requestId`. - For target player-admission calls only, the minimum request additionally carries `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. Game Session supplies these fields as trusted typed execution/request context; the private `game-session-account-delegation` JWT carries its declared Account authority but does not carry `verifiedConnectScopeId` or the complete runtime target bundle. Account requires `callerAccountId` to equal the authenticated delegation JWT's `accountId`/`sub` and the exact bound Game Session subject, then verifies the scope and target fields against the signed connect scope and current exact target before returning the already-declared caller/target-bound evidence. World Management's tenant/operation-bound lifecycle calls retain their separate operation context and do not fabricate player-binding fields. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 8854ac3903..d9b489fea8 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -194,3 +194,8 @@ Entry format: - Context: exact Account PostgreSQL CI36888416843 executed all14required UUID/OTP/HTTP cases but failed one setup with `UnfinishedStubbingException`; its stack crossed the persistence-exception-translation proxy while configuring `doAnswer`. - Observation: a prior green run did not establish stable spy setup. The fixture correction unwraps the ultimate Mockito target for setup and verification, while production calls still traverse the injected Spring proxy and the real owner transaction. A separately logged scheduled-cleanup warning is not proved to cause this failure. - Expected pattern: use `AopTestUtils.getUltimateTargetObject` when configuring a proxied spy, preserve the actual proxy on the tested call path and retain transaction/no-mutation assertions. Require executed runner proof for the corrected setup; local compilation and Docker-skipped tests cannot establish recovery. + +- `2026-10-02`: Bind test servers before discovering their ephemeral port + - Context: the consolidated Unit 1B Game Session check failed `WorldManagementStubServerTest.unknownRoomInstanceIdReturnsNotFound` before its behavior assertion with `Address already in use` on a port selected by `TestSocketUtils.findAvailableTcpPort`. + - Observation: checking a free port and releasing it before the actual bind leaves a race. The existing stub already accepts port zero and reports its bound port; its three tests now use that interface without changing their domain assertions. The colliding process was not identified. All three tests and the complete corrected Account/Game Session/Common Test Support check subsequently passed, establishing local recovery without a domain-assertion change. + - Expected pattern: use kernel-assigned port-zero binding and the started server's actual port when the fixture supports it, rather than an unreserved free-port probe. Do not weaken an assertion or label a failure as flaky without its exact bind evidence. 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 96a59d9013..4bf879df5a 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,12 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The held-back Account runtime membership encoder now carries explicit `authorityAvailability=AVAILABLE` only after the existing complete snapshot checks. Game Session requires that exact value before admission, `JOIN_REQUIRED` or non-public enrollment outcomes; missing, unknown and `UNAVAILABLE` values remain `AUTH_UNAVAILABLE`, never absent membership. Fifteen new public/non-public lifecycle negative cases prove no downstream admission or mutation, while the existing ACTIVE/INACTIVE/never-joined producer assertions carry availability. Canonical UUID request/response echoes remain unchanged, and unsupported advanced authority still denies. The live RPC remains disabled: this component does not supply authenticated positive producer/consumer or full authority-bundle proof. + +The corrected local Account/Game Session/Common Test Support full checks, both service JARs, formatting/static analysis and docs passed166tasks(25executed/141up-to-date). Game Session executed1,764unit,18non-PostgreSQL integration and1cross-service cases with zero failures/errors;17unit,133integration and33cross-service cases skipped. Account's508unit and Common Test Support's43unit executions passed in the preceding same-code run and were up-to-date in the final gate; all159Account PostgreSQL cases compiled/discovered but skipped locally. The first combined gate failed only in an unchanged World stub's unreserved free-port bind before its assertion; the three tests now use the existing port-zero/actual-bound-port interface and all passed. See the dated [AI observation](../ai-observations.md). These are local component checks, not fresh-image or live runtime proof. + +Exact registration head `91c062f6b43159ee57a3d53c82e940014728047f` [CI36894720732](https://github.com/benhook1013/FireMUD/actions/runs/36894720732) completed FAILURE. Account's strict UUID/OTP/bootstrap12 plus HTTP2 and Game Session command5 all passed with zero skips/failures/errors. The full Account job executed163integration cases without skips and failed the public registration HTTP assertion because it still searched for the old numeric audit payload; the separate UUID audit readback passed. The corrected HTTP test now compares the exact persisted UUID payload and textual response ID, keeps all no-membership/profile assertions, and is explicitly required in early strict CI. The composite blocking method passed in report evidence, but the later strict generation verifier skipped after the full-check failure. Corrected-head PostgreSQL proof remains required; no full Account success is attributed to that failed run. + Registration and the Account component of the local export now emit the exact persisted canonical UUID as `AccountDto.id`; `CreateAccount` returns it unchanged, and new `ACCOUNT_REGISTERED` platform audit payloads bind that same UUID. The private numeric row key remains only an Account-owned storage selector. The unused reverse DTO-to-entity mapper is removed; no UUID-to-numeric compatibility path is added and retained audit history is not rewritten. Export verifies UUID/provenance/source-row readback before profile reads, with unmapped and contradictory identity denial tests. Profile and tenant DTO identities remain open migration work. The affected full Account check/JAR and docs passed70tasks(42executed/28up-to-date);508unit cases executed without failures/errors/skips, while all159PostgreSQL cases compiled/discovered but skipped without Docker. Updated registration UUID/private-row and exact durable-audit assertions still require corrected-head runner execution. No credential, membership RPC, catalog or ring mount is enabled. Exact bootstrap UUID source `56a222bf289caa710285bf8655eee1d04161b22e` [CI36888416843](https://github.com/benhook1013/FireMUD/actions/runs/36888416843) executed all12Account UUID/OTP/bootstrap and2HTTP cases without skips. Thirteen passed, including the three new bootstrap UUID cases; one existing OTP case failed during Mockito setup through a Spring repository proxy, not at its persistence assertion. The corrected fixture configures and verifies ultimate Mockito targets while the tested service still uses its real injected proxies and owner transaction. A separate scheduled-cleanup warning is not established as the cause. Corrected-head runner proof remains required. diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 85a725081f..a4de7da821 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -164,6 +164,7 @@ message GetTenantMembershipForRuntimeResponse { string request_account_id = 18; // Exact canonical UUID echo of player_context.account_id. string request_tenant_id = 19; // Exact canonical UUID echo of player_context.tenant_id. string request_id = 20; + string authority_availability = 21; } message RuntimeMembershipBaseline { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index ee731fe806..7e7ab50552 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -481,6 +481,7 @@ static GetTenantMembershipForRuntimeResponse encodeRuntimeMembershipCandidate( .setRequestAccountId(playerContext.getAccountId()) .setRequestTenantId(playerContext.getTenantId()) .setRequestId(playerContext.getRequestId()) + .setAuthorityAvailability("AVAILABLE") .setGameplayAdmissionAllowed(snapshot.gameplayAdmissionAllowed()) .setMembershipExists(snapshot.membershipExists()) .setMembershipLifecycleState(baseline.membershipLifecycleState()) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index 691667a302..aca3f5a666 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -44,6 +44,8 @@ import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -58,6 +60,7 @@ }) class AccountApplicationIntegrationTest { private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); + private static final ObjectMapper JSON = new ObjectMapper(); @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -116,6 +119,10 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws dsl.resultQuery("SELECT account_uuid FROM accounts WHERE email = ?", email) .fetchOne(0, UUID.class); assertThat(accountUuid).isNotNull(); + JsonNode responseData = JSON.readTree(response.body()).path("data"); + assertThat(responseData.path("id").isTextual()).isTrue(); + assertThat(responseData.path("id").asText()).isEqualTo(accountUuid.toString()); + assertThat(responseData.path("id").asText()).isNotEqualTo(accountId.toString()); assertThat( dsl.resultQuery( "SELECT COUNT(*) FROM account_authority_generations " @@ -174,7 +181,7 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws "SELECT COUNT(*) FROM account_audit_outbox " + "WHERE scope = 'platform' AND tenant_id IS NULL " + "AND event_type = 'ACCOUNT_REGISTERED' AND payload = ?", - "{\"accountId\":" + accountId.longValue() + "}")) + "{\"accountId\":\"" + accountUuid + "\"}")) .isEqualTo(1L); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 2dbf6d1c63..3ce3da4826 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -1904,6 +1904,7 @@ void encodeRuntimeMembershipCandidateEncodesCompleteActivePositiveSnapshot() { assertEquals(ACCOUNT_UUID, response.getRequestAccountId()); assertEquals(TENANT_UUID, response.getRequestTenantId()); assertEquals("membership-read-1", response.getRequestId()); + assertEquals("AVAILABLE", response.getAuthorityAvailability()); assertTrue(response.getMembershipExists()); assertTrue(response.getGameplayAdmissionAllowed()); assertEquals("ACTIVE", response.getMembershipLifecycleState()); @@ -1953,6 +1954,7 @@ void encodeRuntimeMembershipCandidateEncodesInactivePositiveSnapshotWithoutAdmis assertTrue(response.getMembershipExists()); assertFalse(response.getGameplayAdmissionAllowed()); + assertEquals("AVAILABLE", response.getAuthorityAvailability()); assertEquals("INACTIVE", response.getMembershipLifecycleState()); assertEquals(List.of("player"), response.getRolesList()); assertEquals(Map.of(TENANT_UUID, "3"), response.getMembershipVersionMap()); @@ -2129,6 +2131,7 @@ void encodeRuntimeMembershipCandidateEncodesNeverJoinedSequenceZeroSnapshot() { assertEquals(ACCOUNT_UUID, response.getAccountId()); assertEquals(TENANT_UUID, response.getTenantId()); assertEquals("membership-read-1", response.getRequestId()); + assertEquals("AVAILABLE", response.getAuthorityAvailability()); assertFalse(response.getMembershipExists()); assertFalse(response.getGameplayAdmissionAllowed()); assertEquals("MISSING", response.getMembershipLifecycleState()); diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index d203286814..ca7ed5a663 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -260,6 +260,7 @@ private static GetTenantMembershipForRuntimeResponse completeMembershipSnapshot( .setRequestAccountId(accountSelector) .setRequestTenantId(tenantSelector) .setRequestId(requestId) + .setAuthorityAvailability("AVAILABLE") .setMembershipExists(exists) .setMembershipLifecycleState(lifecycle) .setGameplayAdmissionAllowed(admitted) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index bccfebe7c0..e2c5280508 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -1300,7 +1300,8 @@ private boolean isSafeMembershipAuthorityResponse( SessionContext context, GameplayWorldCatalog.RealmView selectedRealm, String requestId) { - if (!StringUtils.hasText(response.getAccountId()) + if (!"AVAILABLE".equals(response.getAuthorityAvailability()) + || !StringUtils.hasText(response.getAccountId()) || !StringUtils.hasText(response.getTenantId()) || !StringUtils.hasText(response.getEvaluatedAt()) || !isCanonicalUuid(response.getAccountId()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 5d6212b61a..d62cb62b8f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -45,6 +45,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; @@ -2208,6 +2209,116 @@ void playWhenMembershipAuthorityUnavailableFailsClosed(String errorCode) { Mockito.verify(sessionContextService, Mockito.never()).save(Mockito.any()); } + @ParameterizedTest + @CsvSource({ + "ACTIVE,ABSENT", + "ACTIVE,UNKNOWN", + "ACTIVE,UNAVAILABLE", + "MISSING,ABSENT", + "MISSING,UNKNOWN", + "MISSING,UNAVAILABLE", + "INACTIVE,ABSENT", + "INACTIVE,UNKNOWN", + "INACTIVE,UNAVAILABLE" + }) + void playRequiresExplicitAvailableMembershipAuthorityBeforePublicOutcomes( + String lifecycle, String availability) { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> { + var membership = + switch (lifecycle) { + case "ACTIVE" -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .active(123L, 22L, "1"); + case "MISSING" -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .missing(123L, 22L); + case "INACTIVE" -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .inactive(123L, 22L, "3"); + default -> + throw new IllegalArgumentException("Unexpected lifecycle: " + lifecycle); + }; + var builder = freshMembership(membership).toBuilder(); + if (!"ABSENT".equals(availability)) { + builder.setAuthorityAvailability(availability); + } else { + builder.clearAuthorityAvailability(); + } + return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId(builder.build(), invocation.getArgument(0)); + }); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verifyNoInteractions( + entityManagementClient, + sessionContextService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + } + + @ParameterizedTest + @CsvSource({ + "MISSING,ABSENT", + "MISSING,UNKNOWN", + "MISSING,UNAVAILABLE", + "INACTIVE,ABSENT", + "INACTIVE,UNKNOWN", + "INACTIVE,UNAVAILABLE" + }) + void playRequiresExplicitAvailableMembershipAuthorityBeforeNonPublicOutcome( + String lifecycle, String availability) { + SessionContext context = unboundContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> { + var membership = + "MISSING".equals(lifecycle) + ? net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .missing(123L, 22L) + : net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .inactive(123L, 22L, "3"); + var builder = freshMembership(membership).toBuilder(); + if (!"ABSENT".equals(availability)) { + builder.setAuthorityAvailability(availability); + } else { + builder.clearAuthorityAvailability(); + } + return net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId(builder.build(), invocation.getArgument(0)); + }); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verify(accountClient, never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.verifyNoInteractions( + entityManagementClient, + sessionContextService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + } + @Test void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { SessionContext context = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java index b14fe5c6d6..242d408a9c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java @@ -12,16 +12,14 @@ import net.firedevops.firemud.worldmanagement.v1.GetRoomSnapshotResponse; import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; import org.junit.jupiter.api.Test; -import org.springframework.test.util.TestSocketUtils; class WorldManagementStubServerTest { @Test void returnsRoomSnapshotForRequestedRoomInstanceId() throws Exception { - int port = TestSocketUtils.findAvailableTcpPort(); - try (WorldManagementStubServer server = new WorldManagementStubServer(port)) { + try (WorldManagementStubServer server = new WorldManagementStubServer(0)) { ManagedChannel channel = - ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build(); + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); try { WorldManagementServiceGrpc.WorldManagementServiceBlockingStub stub = WorldManagementServiceGrpc.newBlockingStub(channel); @@ -60,10 +58,9 @@ void returnsRoomSnapshotForRequestedRoomInstanceId() throws Exception { @Test void returnsRoomSnapshotInTheRequestedRuntimeScope() throws Exception { - int port = TestSocketUtils.findAvailableTcpPort(); - try (WorldManagementStubServer server = new WorldManagementStubServer(port)) { + try (WorldManagementStubServer server = new WorldManagementStubServer(0)) { ManagedChannel channel = - ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build(); + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); try { WorldManagementServiceGrpc.WorldManagementServiceBlockingStub stub = WorldManagementServiceGrpc.newBlockingStub(channel); @@ -92,10 +89,9 @@ void returnsRoomSnapshotInTheRequestedRuntimeScope() throws Exception { @Test void unknownRoomInstanceIdReturnsNotFound() throws Exception { - int port = TestSocketUtils.findAvailableTcpPort(); - try (WorldManagementStubServer server = new WorldManagementStubServer(port)) { + try (WorldManagementStubServer server = new WorldManagementStubServer(0)) { ManagedChannel channel = - ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build(); + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); try { WorldManagementServiceGrpc.WorldManagementServiceBlockingStub stub = WorldManagementServiceGrpc.newBlockingStub(channel); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java index e566df0f41..ea04481043 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/RuntimeMembershipTestFixtures.java @@ -146,6 +146,7 @@ private static GetTenantMembershipForRuntimeResponse complete( .setTenantId(tenantUuid) .setRequestAccountId(Long.toString(accountId)) .setRequestTenantId(Long.toString(tenantId)) + .setAuthorityAvailability("AVAILABLE") .setMembershipExists(exists) .setMembershipLifecycleState(lifecycle) .setGameplayAdmissionAllowed(admitted) From c8444bb1af61ac1d3682b15af7573d7f15a453ff Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 09:48:53 +1300 Subject: [PATCH 14/23] Deny unsupported legacy realm grant mutations without data access --- .../account-service/api-contracts.md | 2 +- .../account-service/runtime-and-data.md | 2 +- .../player-access-and-session.md | 2 + .../controller/InternalRuntimeController.java | 40 +++------ .../service/impl/AccountServiceImpl.java | 39 +-------- .../InternalRuntimeControllerTest.java | 86 +++++++++++++++++++ .../service/impl/AccountServiceImplTest.java | 50 +++++++---- 7 files changed, 137 insertions(+), 84 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 7e0cc38129..129ffee89b 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -54,7 +54,7 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status -Explicit playtest grants remain partial: current Account persistence and internal lookup can support a grant-backed admission read, but expiry bounded by fork lifecycle, tenant-admin create/extend/list/revoke, distinct audited platform break-glass, stable request-idempotent outcomes, retained revocation tombstones, and active-binding ejection are not implemented or end-to-end proved. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. +Explicit playtest grants remain partial. Legacy four-field persistence is retained, but current runtime grant RPC reads deny before data access and those rows do not authorize non-public discovery or admission. Legacy `POST` and `DELETE /internal/runtime/realm-access-grants` retain their authentication and malformed-input checks, then return `AUTH_UNAVAILABLE` before service dispatch; the corresponding direct service mutators also deny before reads or writes. A global privileged-role claim is not the lifecycle-qualified tenant-admin or Account-authorized operator evidence required by the target contract. No legacy grant row is created, revised or deleted through these unsupported mutations. Expiry bounded by fork lifecycle, tenant-admin create/extend/list/revoke, distinct audited platform break-glass, stable request-idempotent outcomes, retained revocation tombstones, and active-binding ejection remain unimplemented or unproved. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. The hosted Creator Party, terms catalog, acceptance/currentness evidence, and changed-term lifecycle are target-only. No current Account route, proto/schema, storage, signer/transfer operation, creator UI, or focused proof implements them; Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 0ff96140e4..d88c51343e 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -293,7 +293,7 @@ Account evaluates effective access as `min(grantExpiresAt, forkExpiresAt)` and e Grant `scopeId`, `outboxStreamKey`, and event `sourceScope` are produced and parsed through the [canonical grant authority-stream scope codec](../../system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). This document owns only the persistence and projection consequences; it does not define another stream grammar or fallback identity. -Current `AccountRealmAccessGrant` persistence is limited to the legacy four-field identity; current Game Session grant gRPC reads fail with `FAILED_PRECONDITION` before data access, so downstream text `PLAY` does not reach grant evaluation. No lifecycle-bound read, expiry, fork-expiry evaluation, tenant-admin mutation surface, expected-revision CAS, request-replay record, durable tombstone, revocation propagation, consumer reconciliation, active-binding ejection, or complete grant event proof exists. During the direct pre-v1 cutover, records lacking `playtestLifecycleId` are invalidated or denied and must be regranted under the exact lifecycle; this local status does not add an alias or compatibility path. The gap statement is intentionally local; endpoint ownership and mutation outcomes remain in [Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract) and [ADR 0138](../../decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md). +Current `AccountRealmAccessGrant` persistence is limited to the legacy four-field identity; current Game Session grant gRPC reads fail with `FAILED_PRECONDITION` before data access, so downstream text `PLAY` does not reach grant evaluation. The unsupported legacy grant and revoke HTTP entries and direct service mutators now deny before grant reads or writes. Existing rows, versions and history remain unchanged; hard-deleting a legacy row is not a substitute for a lifecycle-bound revocation tombstone. No lifecycle-bound read, expiry, fork-expiry evaluation, tenant-admin mutation surface, expected-revision CAS, request-replay record, durable tombstone, revocation propagation, consumer reconciliation, active-binding ejection, or complete grant event proof exists. During the direct pre-v1 cutover, records lacking `playtestLifecycleId` are invalidated or denied and must be regranted under the exact lifecycle; this local status does not add an alias or compatibility path. The gap statement is intentionally local; endpoint ownership and mutation outcomes remain in [Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract) and [ADR 0138](../../decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md). ### Runtime Implementation Status and Drift diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 4bf879df5a..b6fba40bd3 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 known legacy realm-grant mutation boundary now fails closed: otherwise-valid authenticated privileged POST/DELETE requests return `AUTH_UNAVAILABLE` before service dispatch, and direct grant/revoke service calls reject before repository access. Malformed and unauthorized requests retain their existing denial checks. This preserves retained four-field grant rows rather than revising them without lifecycle authority or hard-deleting their history. The Account full check, formatting/static analysis, service JAR and documentation passed70tasks(23executed/47up-to-date), with511unit cases executed without skips/failures/errors. Strict readback confirms the two HTTP and two direct-service denial cases each executed once, including changed payload under the same request ID and both verbs' unauthenticated/nonprivileged denial. All159PostgreSQL cases skipped without local Docker; this is unit/no-dispatch proof, not database or deployed runtime proof. It does not implement ADR 0138's lifecycle-qualified authorization, bounded expiry, idempotent mutation, tombstones, event delivery or active-binding ejection; those remain required pre-v1 owner work. No runtime path or Account ring mount is enabled. + The held-back Account runtime membership encoder now carries explicit `authorityAvailability=AVAILABLE` only after the existing complete snapshot checks. Game Session requires that exact value before admission, `JOIN_REQUIRED` or non-public enrollment outcomes; missing, unknown and `UNAVAILABLE` values remain `AUTH_UNAVAILABLE`, never absent membership. Fifteen new public/non-public lifecycle negative cases prove no downstream admission or mutation, while the existing ACTIVE/INACTIVE/never-joined producer assertions carry availability. Canonical UUID request/response echoes remain unchanged, and unsupported advanced authority still denies. The live RPC remains disabled: this component does not supply authenticated positive producer/consumer or full authority-bundle proof. The corrected local Account/Game Session/Common Test Support full checks, both service JARs, formatting/static analysis and docs passed166tasks(25executed/141up-to-date). Game Session executed1,764unit,18non-PostgreSQL integration and1cross-service cases with zero failures/errors;17unit,133integration and33cross-service cases skipped. Account's508unit and Common Test Support's43unit executions passed in the preceding same-code run and were up-to-date in the final gate; all159Account PostgreSQL cases compiled/discovered but skipped locally. The first combined gate failed only in an unchanged World stub's unreserved free-port bind before its assertion; the three tests now use the existing port-zero/actual-bound-port interface and all passed. See the dated [AI observation](../ai-observations.md). These are local component checks, not fresh-image or live runtime proof. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java index 256a95eb9c..a98e355bfc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java @@ -1,10 +1,9 @@ package net.firedevops.firemud.accountservice.controller; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import jakarta.validation.Valid; import net.firedevops.firemud.accountservice.dto.RealmAccessGrantRequest; import net.firedevops.firemud.accountservice.dto.RealmAccessGrantResult; -import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.ApiResponse; import net.firedevops.firemud.common.security.SessionContext; import org.springframework.http.ResponseEntity; @@ -18,30 +17,13 @@ @RestController @RequestMapping("/internal/runtime") public class InternalRuntimeController { - private final AccountService accountService; - - @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "AccountService is injected and not exposed") - public InternalRuntimeController(AccountService accountService) { - this.accountService = accountService; - } - @PostMapping("/realm-access-grants") public ResponseEntity> grantRealmAccess( @Valid @RequestBody RealmAccessGrantRequest request) { SessionContext.requireGlobalPrivilegedRole(); - RealmAccessGrantRequest normalizedRequest = - new RealmAccessGrantRequest( - AccountRequestReaders.requireAccountId(request.accountId()), - AccountRequestReaders.requireTenantId(request.tenantId()), - request.worldSlug(), - request.realmSlug(), - request.grantedBy(), - request.grantReason(), - request.requestId()); - return ResponseEntity.ok( - ApiResponse.success(accountService.grantRealmAccess(normalizedRequest))); + AccountRequestReaders.requireAccountId(request.accountId()); + AccountRequestReaders.requireTenantId(request.tenantId()); + throw grantMutationUnavailable(); } @DeleteMapping("/realm-access-grants") @@ -51,11 +33,13 @@ public ResponseEntity> revokeRealmAccess( @RequestParam("worldSlug") String worldSlug, @RequestParam("realmSlug") String realmSlug) { SessionContext.requireGlobalPrivilegedRole(); - accountService.revokeRealmAccess( - AccountRequestReaders.requireAccountId(accountId), - AccountRequestReaders.requireTenantId(tenantId), - worldSlug, - realmSlug); - return ResponseEntity.ok(ApiResponse.success(null)); + AccountRequestReaders.requireAccountId(accountId); + AccountRequestReaders.requireTenantId(tenantId); + throw grantMutationUnavailable(); + } + + private static AuthenticationException grantMutationUnavailable() { + return new AuthenticationException( + "AUTH_UNAVAILABLE", "Lifecycle-qualified realm-grant mutations are unavailable"); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 07d20ef961..c8b6407003 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -60,7 +60,6 @@ import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthMode; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; -import net.firedevops.firemud.accountservice.entity.AccountRealmAccessGrant; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.entity.EmailVerificationToken; import net.firedevops.firemud.accountservice.entity.Profile; @@ -1429,47 +1428,17 @@ public RealmAccessGrantResult getRealmAccessGrantForRuntime( } @Override - @Transactional @Timed(value = "account.realm_access_grant_upsert") public RealmAccessGrantResult grantRealmAccess(RealmAccessGrantRequest request) { - Account account = requireAccount(request.accountId()); - Instant now = Instant.now(); - AccountRealmAccessGrant grant = - accountRealmAccessGrantRepository - .findByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - request.accountId(), request.tenantId(), request.worldSlug(), request.realmSlug()) - .orElseGet( - () -> { - AccountRealmAccessGrant created = new AccountRealmAccessGrant(); - created.setAccount(account); - created.setTenantId(request.tenantId()); - created.setWorldSlug(request.worldSlug()); - created.setRealmSlug(request.realmSlug()); - created.setGrantVersion(0L); - created.setCreatedAt(now); - return created; - }); - grant.setGrantVersion(grant.getGrantVersion() + 1L); - grant.setGrantedBy(request.grantedBy()); - grant.setGrantReason(request.grantReason()); - grant.setUpdatedAt(now); - accountRealmAccessGrantRepository.save(grant); - return new RealmAccessGrantResult( - request.accountId(), - request.tenantId(), - request.worldSlug(), - request.realmSlug(), - true, - grant.getGrantVersion(), - now.toString()); + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Lifecycle-qualified realm-grant mutations are unavailable"); } @Override - @Transactional @Timed(value = "account.realm_access_grant_revoke") public void revokeRealmAccess(Long accountId, Long tenantId, String worldSlug, String realmSlug) { - accountRealmAccessGrantRepository.deleteByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - accountId, tenantId, worldSlug, realmSlug); + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Lifecycle-qualified realm-grant mutations are unavailable"); } @Override diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/InternalRuntimeControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/InternalRuntimeControllerTest.java index ebc10dc331..24c466f293 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/InternalRuntimeControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/InternalRuntimeControllerTest.java @@ -6,6 +6,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import net.firedevops.firemud.accountservice.dto.RealmAccessGrantRequest; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; import net.firedevops.firemud.common.config.CommonSecurityServletAutoConfiguration; @@ -90,4 +91,89 @@ void revokeRealmAccessRejectsMalformedAccountIdBeforeDispatch() throws Exception verifyNoInteractions(accountService); } + + @Test + void validPrivilegedGrantMutationsFailClosedBeforeDispatch() throws Exception { + for (String role : java.util.List.of("platformAdmin", "moderator")) { + String token = jwtTokenWithGlobalRole(role); + + mockMvc + .perform( + post("/internal/runtime/realm-access-grants") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) + .contentType(MediaType.APPLICATION_JSON) + .content(validGrantRequestBody())) + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.error.code").value("AUTH_UNAVAILABLE")) + .andExpect( + jsonPath("$.error.message") + .value("Lifecycle-qualified realm-grant mutations are unavailable")); + + mockMvc + .perform( + delete("/internal/runtime/realm-access-grants") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) + .param("accountId", "11") + .param("tenantId", "7") + .param("worldSlug", "demo") + .param("realmSlug", "preview")) + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.error.code").value("AUTH_UNAVAILABLE")) + .andExpect( + jsonPath("$.error.message") + .value("Lifecycle-qualified realm-grant mutations are unavailable")); + } + + verifyNoInteractions(accountService); + } + + @Test + void missingOrNonprivilegedAuthenticationStillDeniesGrantMutations() throws Exception { + mockMvc + .perform( + post("/internal/runtime/realm-access-grants") + .contentType(MediaType.APPLICATION_JSON) + .content(validGrantRequestBody())) + .andExpect(status().isUnauthorized()); + + mockMvc + .perform( + delete("/internal/runtime/realm-access-grants") + .param("accountId", "11") + .param("tenantId", "7") + .param("worldSlug", "demo") + .param("realmSlug", "preview")) + .andExpect(status().isUnauthorized()); + + String playerToken = jwtTokenWithGlobalRole("player"); + mockMvc + .perform( + post("/internal/runtime/realm-access-grants") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + playerToken) + .contentType(MediaType.APPLICATION_JSON) + .content(validGrantRequestBody())) + .andExpect(status().isForbidden()); + + mockMvc + .perform( + delete("/internal/runtime/realm-access-grants") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + jwtTokenWithGlobalRole("player")) + .param("accountId", "11") + .param("tenantId", "7") + .param("worldSlug", "demo") + .param("realmSlug", "preview")) + .andExpect(status().isForbidden()); + + verifyNoInteractions(accountService); + } + + private String jwtTokenWithGlobalRole(String role) { + return jwtUtil.generateToken("user", java.util.Map.of("globalRoles", java.util.List.of(role))); + } + + private String validGrantRequestBody() throws Exception { + return objectMapper.writeValueAsString( + new RealmAccessGrantRequest( + 11L, 7L, "demo", "preview", "operator", "preview access", "request-1")); + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 4cade89bb7..3d1175723d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -4970,27 +4970,39 @@ void issueConnectTokenRequiresMembershipForPrivateTargetDespiteLegacyGrant() { } @Test - void grantRealmAccessUpsertsRuntimeGrant() { - Account account = new Account(); - account.setId(11L); - account.setUsername("demo"); - when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); - when(accountRealmAccessGrantRepository.findByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "preview")) - .thenReturn(Optional.empty()); - when(accountRealmAccessGrantRepository.save( - org.mockito.ArgumentMatchers.any(AccountRealmAccessGrant.class))) - .thenAnswer(invocation -> invocation.getArgument(0)); + void grantRealmAccessFailsClosedForRepeatedAndChangedLegacyRequests() { + RealmAccessGrantRequest originalRequest = + new RealmAccessGrantRequest( + 11L, 7L, "demo", "preview", "operator", "preview access", "req-grant-1"); + RealmAccessGrantRequest changedRequest = + new RealmAccessGrantRequest( + 11L, 7L, "demo", "preview", "different operator", "changed reason", "req-grant-1"); + + for (RealmAccessGrantRequest request : + java.util.List.of(originalRequest, originalRequest, changedRequest)) { + AuthenticationException exception = + assertThrows(AuthenticationException.class, () -> service.grantRealmAccess(request)); + assertEquals("AUTH_UNAVAILABLE", exception.getCode()); + assertEquals( + "Lifecycle-qualified realm-grant mutations are unavailable", exception.getMessage()); + } - var result = - service.grantRealmAccess( - new RealmAccessGrantRequest( - 11L, 7L, "demo", "preview", "operator", "preview access", "req-grant-1")); + verifyNoInteractions(accountRepository, accountRealmAccessGrantRepository); + } - assertTrue(result.granted()); - assertEquals(1L, result.grantVersion()); - org.mockito.Mockito.verify(accountRealmAccessGrantRepository) - .save(org.mockito.ArgumentMatchers.any(AccountRealmAccessGrant.class)); + @Test + void revokeRealmAccessFailsClosedForRepeatedAndChangedLegacyRequests() { + for (long accountId : java.util.List.of(11L, 11L, 12L)) { + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.revokeRealmAccess(accountId, 7L, "demo", "preview")); + assertEquals("AUTH_UNAVAILABLE", exception.getCode()); + assertEquals( + "Lifecycle-qualified realm-grant mutations are unavailable", exception.getMessage()); + } + + verifyNoInteractions(accountRepository, accountRealmAccessGrantRepository); } @Test From 53479c7d5718fbb3269da83a89725f19b669c752 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 21:54:42 +1300 Subject: [PATCH 15/23] Resolve authored-world source before short owner intake transaction --- ...GameSessionAuthoredWorldIntakeService.java | 23 ++-- ...SessionAuthoredWorldIntakeServiceTest.java | 127 +++++++++++++++--- 2 files changed, 125 insertions(+), 25 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeService.java index a6305ee1c5..c79a5c5d66 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeService.java @@ -8,9 +8,10 @@ import net.firedevops.firemud.gamesession.client.GameDesignRuntimeTenantIdentityClient; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; /** * Unwired Game Session source intake. Only an authenticated exact Game Design read can reach local @@ -20,29 +21,35 @@ public class GameSessionAuthoredWorldIntakeService { private final GameDesignRuntimeTenantIdentityClient sourceClient; private final GameSessionAuthoredWorldSourceRepository repository; private final String workloadNamespace; + private final TransactionTemplate ownerTransaction; @SuppressFBWarnings( value = "CT_CONSTRUCTOR_THROW", justification = - "Trusted owner configuration is validated before use; no resources or finalizer are acquired." - + " The class remains non-final for transaction proxying.") + "Trusted owner configuration is validated before use; no resources or finalizer are acquired.") public GameSessionAuthoredWorldIntakeService( GameDesignRuntimeTenantIdentityClient sourceClient, GameSessionAuthoredWorldSourceRepository repository, + PlatformTransactionManager transactionManager, String workloadNamespace) { this.sourceClient = Objects.requireNonNull(sourceClient, "sourceClient"); this.repository = Objects.requireNonNull(repository, "repository"); + Objects.requireNonNull(transactionManager, "transactionManager"); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { throw new IllegalArgumentException("Game Session workload namespace is invalid"); } this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); } - @Transactional(propagation = Propagation.MANDATORY) + /** Resolves the authenticated source before opening a short local owner transaction. */ public IntakeReceipt intake( UUID intakeRequestId, UUID canonicalTenantId, UUID sourceOperationId, String worldSlug) { - if (!TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException("Authored-world intake requires its owner transaction"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source read must begin outside an owner transaction"); } requireIdentity(intakeRequestId, "intakeRequestId"); requireIdentity(sourceOperationId, "sourceOperationId"); @@ -61,7 +68,7 @@ public IntakeReceipt intake( || !worldSlug.equals(source.worldSlug())) { throw new IllegalStateException("Authenticated authored-world source does not match intake"); } - return repository.register(intakeRequestId, source); + return ownerTransaction.execute(status -> repository.register(intakeRequestId, source)); } private static void requireIdentity(UUID value, String name) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeServiceTest.java index 9fd8ce4e1b..bcbbf6ecb9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeServiceTest.java @@ -2,8 +2,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -19,6 +22,11 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; import org.springframework.transaction.support.TransactionSynchronizationManager; class GameSessionAuthoredWorldIntakeServiceTest { @@ -31,24 +39,18 @@ class GameSessionAuthoredWorldIntakeServiceTest { mock(GameDesignRuntimeTenantIdentityClient.class); private final GameSessionAuthoredWorldSourceRepository repository = mock(GameSessionAuthoredWorldSourceRepository.class); + private final PlatformTransactionManager transactionManager = + mock(PlatformTransactionManager.class); private final GameSessionAuthoredWorldIntakeService service = - new GameSessionAuthoredWorldIntakeService(client, repository, "firemud"); + new GameSessionAuthoredWorldIntakeService(client, repository, transactionManager, "firemud"); @AfterEach void clearTransaction() { TransactionSynchronizationManager.clear(); } - @Test - void requiresOwnerTransactionBeforeSourceReadOrPersistence() { - assertThatThrownBy(() -> service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)) - .isInstanceOf(IllegalStateException.class); - verifyNoInteractions(client, repository); - } - @Test void rejectsInvalidSelectorsBeforeSourceReadOrPersistence() { - ownerTransaction(); assertThatThrownBy(() -> service.intake(null, TENANT, SOURCE_OPERATION, WORLD)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> service.intake(REQUEST, TENANT, new UUID(0, 0), WORLD)) @@ -57,12 +59,11 @@ void rejectsInvalidSelectorsBeforeSourceReadOrPersistence() { .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> service.intake(REQUEST, TENANT, SOURCE_OPERATION, "Bad-Slug")) .isInstanceOf(IllegalArgumentException.class); - verifyNoInteractions(client, repository); + verifyNoInteractions(client, repository, transactionManager); } @Test void persistsOnlyTheAuthenticatedExactSourceAndKeepsReadIdentitySeparate() { - ownerTransaction(); var source = source("firemud", TENANT, SOURCE_OPERATION, WORLD); var localOperation = UUID.fromString("55555555-5555-4555-8555-555555555555"); var requestDigest = GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, source); @@ -77,10 +78,36 @@ void persistsOnlyTheAuthenticatedExactSourceAndKeepsReadIdentitySeparate() { when(client.resolveAuthoredWorldSource( eq(TENANT.toString()), eq(SOURCE_OPERATION.toString()), eq(WORLD), anyString())) .thenReturn(source); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + }); + doAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(false); + return null; + }) + .when(transactionManager) + .commit(any(TransactionStatus.class)); when(repository.register(REQUEST, source)).thenReturn(receipt); assertThat(service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)).isEqualTo(receipt); - verify(repository).register(REQUEST, source); + InOrder ordered = inOrder(client, transactionManager, repository); + ordered + .verify(client) + .resolveAuthoredWorldSource( + eq(TENANT.toString()), eq(SOURCE_OPERATION.toString()), eq(WORLD), anyString()); + ArgumentCaptor definition = + ArgumentCaptor.forClass(TransactionDefinition.class); + ordered.verify(transactionManager).getTransaction(definition.capture()); + ordered.verify(repository).register(REQUEST, source); + ordered.verify(transactionManager).commit(any(TransactionStatus.class)); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRED); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); var readRequest = ArgumentCaptor.forClass(String.class); verify(client) .resolveAuthoredWorldSource( @@ -95,7 +122,6 @@ void persistsOnlyTheAuthenticatedExactSourceAndKeepsReadIdentitySeparate() { @Test void coherentlyRedigestedWrongScopeCannotReachPersistence() { - ownerTransaction(); var wrongSources = java.util.List.of( source("other", TENANT, SOURCE_OPERATION, WORLD), @@ -108,12 +134,11 @@ void coherentlyRedigestedWrongScopeCannotReachPersistence() { assertThatThrownBy(() -> service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)) .isInstanceOf(IllegalStateException.class); } - verifyNoInteractions(repository); + verifyNoInteractions(repository, transactionManager); } @Test void absentOrUnavailableOwnerCannotLeaveAnyLocalClaim() { - ownerTransaction(); when(client.resolveAuthoredWorldSource(anyString(), anyString(), anyString(), anyString())) .thenReturn(null); assertThatThrownBy(() -> service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)) @@ -123,11 +148,79 @@ void absentOrUnavailableOwnerCannotLeaveAnyLocalClaim() { assertThatThrownBy(() -> service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)) .isInstanceOf(IllegalStateException.class) .hasMessage("source unavailable"); - verifyNoInteractions(repository); + verifyNoInteractions(repository, transactionManager); + } + + @Test + void sourceFetchRunsOutsideTransactionAndRegistrationRunsInside() { + var source = source("firemud", TENANT, SOURCE_OPERATION, WORLD); + var receipt = mock(IntakeReceipt.class); + when(client.resolveAuthoredWorldSource(anyString(), anyString(), anyString(), anyString())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return source; + }); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + }); + when(repository.register(REQUEST, source)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return receipt; + }); + doAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(false); + return null; + }) + .when(transactionManager) + .commit(any(TransactionStatus.class)); + + assertThat(service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)).isSameAs(receipt); } - private static void ownerTransaction() { + @Test + void registrationFailureRollsBackOwnerTransaction() { + var source = source("firemud", TENANT, SOURCE_OPERATION, WORLD); + when(client.resolveAuthoredWorldSource(anyString(), anyString(), anyString(), anyString())) + .thenReturn(source); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + }); + doAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(false); + return null; + }) + .when(transactionManager) + .rollback(any(TransactionStatus.class)); + when(repository.register(REQUEST, source)).thenThrow(new IllegalStateException("write failed")); + + assertThatThrownBy(() -> service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("write failed"); + + verify(transactionManager).rollback(any(TransactionStatus.class)); + verify(transactionManager, org.mockito.Mockito.never()).commit(any(TransactionStatus.class)); + } + + @Test + void activeCallerTransactionIsRejectedBeforeSourceReadOrOwnerTransaction() { TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> service.intake(REQUEST, TENANT, SOURCE_OPERATION, WORLD)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an owner transaction"); + + verifyNoInteractions(client, repository, transactionManager); } private static AuthoredWorldSourceEvidence source( From 6da02cbe7c25cb4d20b90417eeffd919648e7f1d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 00:39:26 +1300 Subject: [PATCH 16/23] Classify retained association read failures accurately --- .../impl/TenantIdentityGrpcService.java | 10 ++- .../GameSessionTenantAssociationGrpcTest.java | 61 ++++++++++++++++++- 2 files changed, 68 insertions(+), 3 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java index b1e425c5fa..cd3e7c8a53 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcService.java @@ -570,12 +570,20 @@ public void resolveLegacyGameSessionTenantAssociation( .withDescription("Retained Game Session association evidence is inconsistent") .asRuntimeException()); return; - } catch (DataAccessException | DataAccessResourceFailureException ex) { + } catch (DataAccessResourceFailureException ex) { responseObserver.onError( Status.UNAVAILABLE .withDescription("Retained Game Session association could not be read") .asRuntimeException()); return; + } catch (DataAccessException ex) { + Status.Code code = + hasConnectionFailureSqlState(ex) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription("Retained Game Session association could not be read") + .asRuntimeException()); + return; } if (resolved.isEmpty()) { responseObserver.onError( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java index c4e1388950..10071f8f32 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameSessionTenantAssociationGrpcTest.java @@ -9,6 +9,7 @@ import io.grpc.Context; import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.sql.SQLException; import java.util.Base64; import java.util.HashSet; import java.util.Optional; @@ -23,10 +24,12 @@ import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyGameSessionTenantAssociationResponse; +import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.Test; import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.env.PropertySource; import org.springframework.core.io.FileSystemResource; +import org.springframework.dao.DataAccessResourceFailureException; class GameSessionTenantAssociationGrpcTest { private static final UUID OPERATION = UUID.fromString("11111111-1111-4111-8111-111111111111"); @@ -135,15 +138,66 @@ void absentContradictoryAndUnavailableEvidenceNeverReturnsPartialContent() { when(repository.read(OPERATION, TENANT, 41L, "test")) .thenReturn(Optional.empty()) .thenThrow(new IllegalStateException("contradictory stored evidence")) - .thenThrow(new org.jooq.exception.DataAccessException("storage unavailable")); + .thenThrow( + new DataAccessException( + "private storage detail", new SQLException("private connection detail", "08006"))); assertThat(call(request(), GAME_SESSION).error).isEqualTo(Status.Code.NOT_FOUND); assertThat(call(request(), GAME_SESSION).error).isEqualTo(Status.Code.FAILED_PRECONDITION); Observer unavailable = call(request(), GAME_SESSION); assertThat(unavailable.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.description) + .isEqualTo("Retained Game Session association could not be read"); assertThat(unavailable.value).isNull(); assertThat(unavailable.completed).isFalse(); } + @Test + void connectionSqlStateFailureIsSanitizedUnavailableWithoutPartialContent() { + when(repository.read(OPERATION, TENANT, 41L, "test")) + .thenThrow( + new DataAccessException( + "private jOOQ detail", + new IllegalStateException( + "private wrapper detail", new SQLException("private SQL detail", "08006")))); + + assertReadFailure(Status.Code.UNAVAILABLE); + } + + @Test + void permanentSqlStateFailureIsSanitizedInternalWithoutPartialContent() { + when(repository.read(OPERATION, TENANT, 41L, "test")) + .thenThrow( + new DataAccessException( + "private jOOQ detail", new SQLException("private SQL detail", "42000"))); + + assertReadFailure(Status.Code.INTERNAL); + } + + @Test + void genericNonconnectionJooqFailureIsSanitizedInternalWithoutPartialContent() { + when(repository.read(OPERATION, TENANT, 41L, "test")) + .thenThrow(new DataAccessException("private jOOQ detail")); + + assertReadFailure(Status.Code.INTERNAL); + } + + @Test + void springResourceFailureIsSanitizedUnavailableWithoutPartialContent() { + when(repository.read(OPERATION, TENANT, 41L, "test")) + .thenThrow(new DataAccessResourceFailureException("private resource detail")); + + assertReadFailure(Status.Code.UNAVAILABLE); + } + + private void assertReadFailure(Status.Code expectedCode) { + Observer observer = call(request(), GAME_SESSION); + assertThat(observer.error).isEqualTo(expectedCode); + assertThat(observer.description) + .isEqualTo("Retained Game Session association could not be read"); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + @Test void changedReadScopeDigestAndSignatureDenyWithoutPartialContent() { GameSessionTenantAssociationEvidence exact = evidence(); @@ -252,6 +306,7 @@ private static final class Observer implements StreamObserver { private ResolveLegacyGameSessionTenantAssociationResponse value; private Status.Code error; + private String description; private boolean completed; @Override @@ -261,7 +316,9 @@ public void onNext(ResolveLegacyGameSessionTenantAssociationResponse value) { @Override public void onError(Throwable error) { - this.error = Status.fromThrowable(error).getCode(); + Status status = Status.fromThrowable(error); + this.error = status.getCode(); + this.description = status.getDescription(); } @Override From 45c0ad8c127a44c05699409870c8560df3811b08 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 04:06:05 +1300 Subject: [PATCH 17/23] Keep LEFT receipt migration after parent receipt guards --- .../implementation-tracking/player-access-and-session.md | 2 +- ...sql => V42__account_membership_left_transition_receipts.sql} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename services/account-service/src/main/resources/db/migration/{V40__account_membership_left_transition_receipts.sql => V42__account_membership_left_transition_receipts.sql} (100%) 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 06863e8014..1f17c5166a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -60,7 +60,7 @@ Exact child head `32fe02cbb342365863b83252c91e26d39173abc3` [CI36844382190](http Exact parent `642d5d9f58d8e383c8614697f88f085ef3f56b39` [CI36835527324](https://github.com/benhook1013/FireMUD/actions/runs/36835527324) passed the strict five-case Game Session authored-world intake proof with zero skips/failures/errors. Account strict JOIN31, exchange9, issuance9, source/history18, association6, pair8, fresh UUID snapshot11 and generation2/outbox4, plus Game Design creation8/authored-source10, also passed without skips/failures/errors. These are runner-JUnit verifier results, not uploaded raw XML. Aggregate CI failed, with Game Session's broader check cancelled after 18 CommunicationWebSocket failures; Script Pin25 and focused WebSocket16 proof are not credited. This parent execution does not prove the new LEFT candidate or enable catalog, membership or credential paths. -2026-10-01 Account has an unwired owner-local LEFT component candidate in `AccountMembershipLifecycleService` with V40 receipt-state support. It accepts only an already-proved retained ACTIVE membership pair and, in one Account owner transaction, marks the retained row INACTIVE/non-admitting, preserves its role set, advances membership version and authority generation, and records the canonical invalidating authority event, provisional transition receipt, audit envelope, and pair authority. Exact replay verifies the original immutable event/receipt/audit result; after reactivation it remains historical readback, not current authority. The held-back current-INACTIVE reader requires the existing pair, membership and roles plus the exact latest positive LEFT receipt and matching current checkpoint/event/fence; it does not accept sequence zero, enroll a missing pair, or authorize admission. Public caller authentication/route, fresh-UUID positive JOIN and lifecycle, advanced upstream authority, delivery/projection and consumer convergence, runtime RPC enablement, and credential/catalog activation remain open. The PostgreSQL cases for LEFT, replay after reactivation, lost acknowledgement, concurrency, contradiction and rollback skipped in the owner-local run without Docker; exact child-head PostgreSQL execution and strict component results are recorded above. [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md), [Authentication](../../architecture/system-architecture-authentication.md), [ADR 0030](../../architecture/decisions/adr-0030-risk-based-active-session-revocation.md), and [ADR 0036](../../architecture/decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md) remain the owners of public lifecycle behavior and authority-generation/revocation semantics. +2026-10-01 Account has an unwired owner-local LEFT component candidate in `AccountMembershipLifecycleService` with receipt-state support, now positioned at V42 after the parent's receipt creation and protection migrations. It accepts only an already-proved retained ACTIVE membership pair and, in one Account owner transaction, marks the retained row INACTIVE/non-admitting, preserves its role set, advances membership version and authority generation, and records the canonical invalidating authority event, provisional transition receipt, audit envelope, and pair authority. Exact replay verifies the original immutable event/receipt/audit result; after reactivation it remains historical readback, not current authority. The held-back current-INACTIVE reader requires the existing pair, membership and roles plus the exact latest positive LEFT receipt and matching current checkpoint/event/fence; it does not accept sequence zero, enroll a missing pair, or authorize admission. Public caller authentication/route, fresh-UUID positive JOIN and lifecycle, advanced upstream authority, delivery/projection and consumer convergence, runtime RPC enablement, and credential/catalog activation remain open. The PostgreSQL cases for LEFT, replay after reactivation, lost acknowledgement, concurrency, contradiction and rollback skipped in the owner-local run without Docker; exact child-head PostgreSQL execution and strict component results are recorded above. [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md), [Authentication](../../architecture/system-architecture-authentication.md), [ADR 0030](../../architecture/decisions/adr-0030-risk-based-active-session-revocation.md), and [ADR 0036](../../architecture/decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md) remain the owners of public lifecycle behavior and authority-generation/revocation semantics. Bounded diagnosis of exact prior-head [CI 36826897436](https://github.com/benhook1013/FireMUD/actions/runs/36826897436) on `ada803afcf69fd69555f5ecad55275e424d8623e`: the new CommunicationWebSocket cases need `OK PLAY` or, where public membership is missing, `JOIN_REQUIRED` to reach their communication assertions, but the production path fails before those assertions. The run logs lack response text; the static carrier trace shows `LOGIN` retains numeric Account ID, `PLAY` builds a numeric Account/tenant `PlayerExecutionContext`, and production `AccountClient` requires canonical non-nil UUIDs and denies before the Account stub, which `PLAY` reports as `AUTH_UNAVAILABLE`. The test stub's numeric UUID formatter is not production identity authority, and its numeric request echoes conflict with the UUID protocol. This is an open identity-carrier prerequisite and failed proof, not evidence of an inherited/flaky failure or a resolved path: genuine Account identity, Game Design/Game Session tenant association, and UUID carriers are still required. diff --git a/services/account-service/src/main/resources/db/migration/V40__account_membership_left_transition_receipts.sql b/services/account-service/src/main/resources/db/migration/V42__account_membership_left_transition_receipts.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V40__account_membership_left_transition_receipts.sql rename to services/account-service/src/main/resources/db/migration/V42__account_membership_left_transition_receipts.sql From fd5b437963434e536c585d3751f5087ccc71b13f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 05:58:42 +1300 Subject: [PATCH 18/23] Preserve parent migration slots and prove child schema ordering --- .../microservices/game-session-service/api-contracts.md | 2 ++ .../microservices/game-session-service/runtime-and-data.md | 4 +++- .../implementation-tracking/player-access-and-session.md | 6 +++--- ...ce_intake.sql => V7.1__authored_world_source_intake.sql} | 0 ...ssociation.sql => V8.1__retained_tenant_association.sql} | 0 ...unt_uuid.sql => V9.1__gameplay_command_account_uuid.sql} | 0 .../GameplayCommandAccountUuidMigrationIntegrationTest.java | 2 +- .../V11__enforce_tenant_public_realm_cardinalityTest.java | 3 +++ 8 files changed, 12 insertions(+), 5 deletions(-) rename services/game-session-service/src/main/resources/db/migration/{V7__authored_world_source_intake.sql => V7.1__authored_world_source_intake.sql} (100%) rename services/game-session-service/src/main/resources/db/migration/{V8__retained_tenant_association.sql => V8.1__retained_tenant_association.sql} (100%) rename services/game-session-service/src/main/resources/db/migration/{V9__gameplay_command_account_uuid.sql => V9.1__gameplay_command_account_uuid.sql} (100%) diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index c7180aa211..7cb3a43f95 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -42,6 +42,8 @@ Game Session consumes the exact authenticated authored-world receipt defined by The separate [audited retained-tenant association](../game-design-service/api-contracts.md#audited-retained-game-session-tenant-association) uses this same Game Design-authenticated client channel but a distinct closed manifest and read method. The client checks the independent request echo, exact namespace/operation/tenant/key binding, complete evidence, canonical signature shape and recomputed digest. It does not persist a local retained association or prove the captured Game Session rows; that owner-fenced snapshot and durable receiver remain required before catalog use. The source digest and historical approval are never gameplay authorization. +The owner-local source intake, retained association, and command UUID schema slots are assigned to Game Session migrations V7.1, V8.1, and V9.1, after distinct parent migrations V7, V8, and V9. This source-tree ordering does not prove a prior deployment's Flyway history or retained-data readback. Before dependent paths activate, exact deployed history and owner-readback of retained rows/evidence must be established; unknown provenance remains unresolved, with no Flyway repair, out-of-order execution, identity casting, or data cleanup. See [runtime and data](./runtime-and-data.md#implementation-status) for the current gate. + Game Session's source intake binds its own stable non-nil UUID `intakeRequestId` to the complete immutable Game Design source receipt under the exact workload namespace. The intake service obtains that receipt through the authenticated Game Design source client using a separate read-attempt identity and verifies the requested source operation, tenant UUID and world selector. Before delivering response headers or content, the source client also checks the authenticated TLS leaf's single exact `spiffe://firemud/ns//sa/game-design-service` URI; a trusted CA or matching DNS name alone cannot substitute for workload identity. Missing, ambiguous, another-service or cross-namespace peers fail closed. A caller-constructed receipt, digest alone, Account migration manifest or unchecked transport is not a source authorization. Game Design remains the normative source owner; Game Session's stored copy is the exact consumed evidence, not a new authored selector issuer. The owner transaction atomically persists the local non-nil UUID operation, immutable source evidence and tenant selector claim. Within a namespace, one tenant UUID has one `tenantSlug`, one `tenantSlug` has one tenant UUID, and each `(tenantId, worldSlug)` has one exact consumed source. Compatible additional worlds reuse the same tenant source claim; a conflicting tenant/world/source or changed request fails without partial claims. Exact retries return the original local operation and receipt without changing rows. The transient read-attempt ID is an authenticated response echo, not a replacement intake request or persisted registration field. Exact committed readback is non-mutating and checks the complete stored source and selector binding; it cannot allocate missing state or choose another candidate. 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 723ac48870..fdd1d3fff6 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,7 +10,9 @@ 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: -- V9 adds a nullable, non-nil `gameplay_command.account_uuid` storage slot and exact repository readback for a verified producer's canonical Account identity. It preserves the complete existing row and numeric `account_id` evidence without deriving or backfilling a UUID. The current command ingress still uses its older carrier until the consumer correction is integrated; retained rows without authenticated mapping cannot become canonical UUID evidence. Storage availability alone does not prove caller authorization, retained-command replay, or activation of the denied credential and membership paths. +- V9.1 adds a nullable, non-nil `gameplay_command.account_uuid` storage slot and exact repository readback for a verified producer's canonical Account identity. It preserves the complete existing row and numeric `account_id` evidence without deriving or backfilling a UUID. The current command ingress still uses its older carrier until the consumer correction is integrated; retained rows without authenticated mapping cannot become canonical UUID evidence. Storage availability alone does not prove caller authorization, retained-command replay, or activation of the denied credential and membership paths. + +- The current Game Session migration order preserves the parent's V7 catalog-revision audit, V8 legacy-bootstrap repair, and V9 initial-admission ledger; this candidate's authored-world source intake, retained tenant association, and command UUID storage are V7.1, V8.1, and V9.1 respectively. These filename changes resolve source-tree version collisions only and do not establish any deployed Flyway history. Before dependent catalog or command paths activate, verify the exact deployed Game Session history and owner-readback of retained source, snapshot, association, and command rows. Preserve all rows and evidence; unknown provenance remains unresolved. Do not use Flyway repair, out-of-order execution, identity casting, or data cleanup to reconcile prior history. No deployed-history or retained-row readback proof is claimed here. - The shared Gateway connect-context codec now declares and verifies the complete signed-context shape and has local vectors, but first-party runtime parsing remains fail-closed. It does not admit the target context until the independent Gateway Ed25519 verification key is published, Account-to-tenant UUID mapping is available, and the real Account exchange/source-evidence path is proved. Codec and vector presence is not a live issuer/consumer handoff or gameplay-admission proof. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 5086f84098..74a9d0f7f0 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -20,7 +20,7 @@ Exact bootstrap UUID source `56a222bf289caa710285bf8655eee1d04161b22e` [CI368884 An additional Account-local PostgreSQL case holds the exact composite generation snapshot, proves that concurrent issuer and tenant advances are blocked by that holder's exact backend, then verifies generation/source-version advancement with the independent Account fence unchanged. It also preserves membership authority when the requested tenant-authority map is empty and rejects a missing membership scope without enrollment. This is a repository linearization prerequisite, not the complete immutable evidence bundle, registry, credential producer, or cross-store authorization. Local Account check/JAR and docs passed70tasks(14executed/56up-to-date); the existing506unit results were up-to-date, not newly executed, and all159PostgreSQL cases compiled/discovered but skipped without Docker. The new method is mandatory in strict CI; executed proof is pending. Runtime RPC, credential/context, catalog and ring-mount gates remain closed. -The Account authentication producer now returns its exact persisted canonical non-nil UUID and signs that same identity in `sub`/`accountId` for password and email-OTP paths. Profile and supported self-service readers first bind the canonical UUID to the authenticated subject, then perform an Account-owned read-only provenance-checked lookup of the private numeric storage key; an unmapped UUID cannot select or mutate another row. Disabled deletion, login-factor mutation and tenant export remain denied without writes. Other numeric DTO, catalog and cross-service consumers are explicitly unfinished; this component does not establish a working end-to-end login/admission path. Game Session V9 separately adds exact command UUID storage without altering or inventing identities for retained numeric rows. The consumer-carrier correction remains a separate unpublished candidate. +The Account authentication producer now returns its exact persisted canonical non-nil UUID and signs that same identity in `sub`/`accountId` for password and email-OTP paths. Profile and supported self-service readers first bind the canonical UUID to the authenticated subject, then perform an Account-owned read-only provenance-checked lookup of the private numeric storage key; an unmapped UUID cannot select or mutate another row. Disabled deletion, login-factor mutation and tenant export remain denied without writes. Other numeric DTO, catalog and cross-service consumers are explicitly unfinished; this component does not establish a working end-to-end login/admission path. Game Session V9.1 separately adds exact command UUID storage without altering or inventing identities for retained numeric rows. The consumer-carrier correction remains a separate unpublished candidate. Local consolidated Account/Game Session full checks and JARs passed (156 tasks, 72 executed/84 up-to-date), including formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown. Account's 502 unit cases passed in the preceding same-code execution; their final task was up-to-date, not a second execution. All 149 Account PostgreSQL cases compiled/discovered and skipped without Docker, including the three new persisted-identity/profile no-mutation cases. Game Session executed 1,747 unit, 18 non-PostgreSQL integration and one cross-service case; 17 unit, 133 integration and 33 cross-service cases skipped, including five new command-storage/migration cases. The earlier possible-null integration fixture readback defect was corrected with explicit required-row checks, not an analyzer suppression. Ring publication infrastructure is an open Platform Operations prerequisite; its mount and all previously denied activation paths remain held back. @@ -38,7 +38,7 @@ Exact published receiver head `2e37b38f5fc022844f97ce654e4678771c620376` [CI3685 That exact run also failed Python lint (10 errors), the Game Design recovery-warning summary contract, Automation PostgreSQL8/69, Game Design EntityDigest duplicate9301 (1/48), and TCP cross-service13/17. The Automation null-base/compensation fixes remain absent upstream ancestry already identified below; the Game Design fixture remains routed to General. No generic flaky/inherited conclusion is inferred for the other failures. Subsequent Account UUID authentication corrections above are excluded from that historical run and do not establish consumer convergence. The membership RPC, credential/context/catalog activation and ring mount remain gated. -2026-10-02 #2923 adds the unwired Game Session owner-local receiver for the separately audited Game Design tenant association. Its closed retained identity snapshot captures all six declared source families under one short READ COMMITTED write fence, rejects incomplete pointers/backfill issues and changed source evidence, and binds the exact namespace, retained key and canonical tenant UUID. The service obtains authenticated Game Design evidence before opening that transaction; V8 then stores the complete immutable approval, snapshot, namespace-qualified one-to-one claims and exact local request/result. Lost-response recovery and exact retry return the original durable evidence without recapturing or rewriting later source state. Neither the service nor association repository is registered as a runtime bean or public route. The canonical contract is [Game Session's retained snapshot and association](../../architecture/microservices/game-session-service/api-contracts.md#retained-tenant-identity-snapshot-and-local-association). +2026-10-02 #2923 adds the unwired Game Session owner-local receiver for the separately audited Game Design tenant association. Its closed retained identity snapshot captures all six declared source families under one short READ COMMITTED write fence, rejects incomplete pointers/backfill issues and changed source evidence, and binds the exact namespace, retained key and canonical tenant UUID. The service obtains authenticated Game Design evidence before opening that transaction; V8.1 then stores the complete immutable approval, snapshot, namespace-qualified one-to-one claims and exact local request/result. Lost-response recovery and exact retry return the original durable evidence without recapturing or rewriting later source state. Neither the service nor association repository is registered as a runtime bean or public route. Renumbering does not prove prior deployed history or retained-data readback; that activation gate remains open as described in [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md#implementation-status). The canonical contract is [Game Session's retained snapshot and association](../../architecture/microservices/game-session-service/api-contracts.md#retained-tenant-identity-snapshot-and-local-association). Local Game Session full check/JAR, Java formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown passed: 123 tasks, 33 executed/90 up-to-date. Tests executed 1,747 unit cases, 18 non-PostgreSQL integration cases and one cross-service case with zero failures/errors; the nine new snapshot/service unit cases all executed. Seventeen unit, 128 integration and 33 cross-service cases skipped. The 12 new PostgreSQL cases (three snapshot-fence and nine association cases) compiled/discovered but all skipped without Docker; the exact runner execution above now supersedes that local-only database limit. Initial delegated import/jOOQ API compile defects and an unnecessary analyzer suppression were corrected without relaxing any assertion or transaction guard. The early strict CI gate requires both suites and their mandatory methods before the broader check. Protected approval custody/import, live authenticated handoff, canonical catalog/carrier convergence and all runtime activation remain open. @@ -52,7 +52,7 @@ The new prerequisite passed local shared-core and Game Design/Game Session full Exact prior child `610ea7b7bcf9f959dbffd452848c710b56e9411b` [CI36839822525](https://github.com/benhook1013/FireMUD/actions/runs/36839822525) executed 38 JOIN/LEFT PostgreSQL cases with five failures and zero skips in the HTML report; the strict Account verifier did not run after the failed full check. Five LEFT paths failed exact audit-envelope readback because append returned the in-memory nanosecond timestamp rather than PostgreSQL's stored timestamp. The correction refreshes the persisted audit record before returning the envelope and propagates unavailable readback; the exact LEFT equality, payload digest and transaction guards are unchanged. Unit proof covers refreshed persisted material; the expanded 39-case PostgreSQL suite includes mandatory exact stored timestamp/envelope readback. Run 36844382190 below supersedes the still-open corrected-candidate database question for its exact child head. The same historical run passed the strict five-case Game Session intake proof; other aggregate identity-carrier, retained-fixture and shared-tooling failures remain open. Metadata-only check success is not new runtime proof. -The Game Session tenant-source client and authored-world intake consumer, V7 schema, tests and focused PostgreSQL gate are owned by successor [#2923](https://github.com/benhook1013/FireMUD/pull/2923), not the reduced #2915 producer checkpoint. #2915 retains Game Design's persisted creation/source producer, closed proto/shared evidence and vectors, Account fresh/retained source and UUID authority, and recovery components. The nine-file consumer package is preserved unchanged in the child; the cumulative capability and activation limits are unchanged. Earlier #2915 intake execution below refers to the exact historical head where that package lived, not new evidence on either redistributed head. Runtime catalog, membership RPC and credential paths remain denied; the retained Game Session association, live authenticated handoff and complete authority/consumer proof remain open. +The Game Session tenant-source client and authored-world intake consumer, V7.1 schema, tests and focused PostgreSQL gate are owned by successor [#2923](https://github.com/benhook1013/FireMUD/pull/2923), not the reduced #2915 producer checkpoint. #2915 retains Game Design's persisted creation/source producer, closed proto/shared evidence and vectors, Account fresh/retained source and UUID authority, and recovery components. The nine-file consumer package is preserved unchanged in the child; the cumulative capability and activation limits are unchanged. Earlier #2915 intake execution below refers to the exact historical head where that package lived, not new evidence on either redistributed head. Runtime catalog, membership RPC and credential paths remain denied; the retained Game Session association, live authenticated handoff and complete authority/consumer proof remain open. The owner-local LEFT candidate passed the consolidated Account/Game Session full checks, affected Java formatting, both service JARs, Checkstyle, SpotBugs, JaCoCo, links, Markdown and Flyway sanity (12 sets/124 files): 153 tasks, 21 executed/132 up-to-date. Account's 469 unit cases and Game Session's 1,731 unit cases executed successfully in the preceding same-code gates; unchanged unit tasks were up-to-date in the final gate. Game Session also executed 18 non-PostgreSQL integration cases and one cross-service case; 17 unit, 116 integration and 33 cross-service cases skipped. All 145 Account PostgreSQL cases, including the expanded 38-case JOIN/LEFT suite and seven required LEFT methods, compiled/discovered but skipped without Docker. Actionlint, all 23 CI-scope contracts and diff hygiene passed. Mocked INACTIVE consumer negatives preserve the production lifecycle guard and distinguish unbound denial from cleanup of an existing binding. Exact-candidate PostgreSQL execution, fresh-image startup and authenticated end-to-end producer/consumer proof remain required; no runtime path is enabled. diff --git a/services/game-session-service/src/main/resources/db/migration/V7__authored_world_source_intake.sql b/services/game-session-service/src/main/resources/db/migration/V7.1__authored_world_source_intake.sql similarity index 100% rename from services/game-session-service/src/main/resources/db/migration/V7__authored_world_source_intake.sql rename to services/game-session-service/src/main/resources/db/migration/V7.1__authored_world_source_intake.sql diff --git a/services/game-session-service/src/main/resources/db/migration/V8__retained_tenant_association.sql b/services/game-session-service/src/main/resources/db/migration/V8.1__retained_tenant_association.sql similarity index 100% rename from services/game-session-service/src/main/resources/db/migration/V8__retained_tenant_association.sql rename to services/game-session-service/src/main/resources/db/migration/V8.1__retained_tenant_association.sql diff --git a/services/game-session-service/src/main/resources/db/migration/V9__gameplay_command_account_uuid.sql b/services/game-session-service/src/main/resources/db/migration/V9.1__gameplay_command_account_uuid.sql similarity index 100% rename from services/game-session-service/src/main/resources/db/migration/V9__gameplay_command_account_uuid.sql rename to services/game-session-service/src/main/resources/db/migration/V9.1__gameplay_command_account_uuid.sql 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 index 03ddebf81d..dd3c120ce7 100644 --- 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 @@ -36,7 +36,7 @@ void migrationRetainsLegacyCommandRowsAndDoesNotInventAccountUuids() { Flyway.configure() .dataSource(dataSource) .locations(MIGRATION_LOCATION) - .target(MigrationVersion.fromVersion("8")) + .target(MigrationVersion.fromVersion("9")) .load() .migrate(); diff --git a/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java b/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java index bbc5f17933..d6ff65dc05 100644 --- a/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java +++ b/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java @@ -46,8 +46,11 @@ void keepsAdmissionPointerMigrationsUniqueAndOrderedFromTheV7AuditThroughV12() assertThat(orderedMigrationNames) .containsSubsequence( "V7__audit_gameplay_catalog_revision.sql", + "V7.1__authored_world_source_intake.sql", "V8__repair_legacy_bootstrap_public_realm.sql", + "V8.1__retained_tenant_association.sql", "V9__initial_admission_bind_owner_ledger.sql", + "V9.1__gameplay_command_account_uuid.sql", "V10__run_owned_initial_launch_identity.sql", "V11__enforce_tenant_public_realm_cardinality.sql", "V12__index_gameplay_admission_pointer_event_tenant_lookup.sql"); From 17d59648fb5a99e420e946c4d9d688ef2110f9f5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 06:32:21 +1300 Subject: [PATCH 19/23] Align composed identity, outbox and LEFT fixtures with stronger parent guards --- .../AccountAuditOutboxRepositoryTest.java | 65 ++++++++++++++----- .../service/impl/AccountServiceImplTest.java | 42 ++++++++---- .../command/text/PlayCommandHandlerTest.java | 10 ++- 3 files changed, 83 insertions(+), 34 deletions(-) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java index 4b45e0c1a7..6e2dc1c782 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java @@ -168,34 +168,35 @@ void appendStoresRetryTimeAsTheSameUtcLocalDateTimeAsOccurredAt() { AtomicReference storedOccurredAt = new AtomicReference<>(); AtomicReference storedNextAttemptAt = new AtomicReference<>(); AtomicReference insertedRow = new AtomicReference<>(); + AtomicReference persistedRow = new AtomicReference<>(); + AtomicReference refreshedRow = new AtomicReference<>(); + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); MockDataProvider provider = context -> { String sql = context.sql().toLowerCase(Locale.ROOT); if (sql.stripLeading().startsWith("insert") && sql.contains("account_audit_outbox")) { executedSql.set(sql); - return new MockResult[] {new MockResult(1)}; - } - if (sql.stripLeading().startsWith("select") && sql.contains("account_audit_outbox")) { AccountAuditOutboxRecord inserted = insertedRow.get(); if (inserted == null) { - throw new SQLException("Audit outbox row was not inserted before readback"); + throw new SQLException("Audit outbox row was not prepared before insert"); } - DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + AccountAuditOutboxRecord persisted = copyAsPersistedRow(resultDsl, inserted); + persistedRow.set(persisted); Result rows = resultDsl.newResult(ACCOUNT_AUDIT_OUTBOX); - AccountAuditOutboxRecord persisted = resultDsl.newRecord(ACCOUNT_AUDIT_OUTBOX); - persisted.setAuditEventId(inserted.getAuditEventId()); - persisted.setScope(inserted.getScope()); - persisted.setTenantId(inserted.getTenantId()); - persisted.setProducerService(inserted.getProducerService()); - persisted.setEventType(inserted.getEventType()); - persisted.setOccurredAt(inserted.getOccurredAt()); - persisted.setSchemaVersion(inserted.getSchemaVersion()); - persisted.setPayloadDigestVersion(inserted.getPayloadDigestVersion()); - persisted.setPayloadDigest(inserted.getPayloadDigest()); - persisted.setPayload(inserted.getPayload()); rows.add(persisted); return new MockResult[] {new MockResult(1, rows)}; } + if (sql.stripLeading().startsWith("select") && sql.contains("account_audit_outbox")) { + AccountAuditOutboxRecord persisted = persistedRow.get(); + if (persisted == null) { + throw new SQLException("Audit outbox row was not inserted before refresh"); + } + Result rows = resultDsl.newResult(ACCOUNT_AUDIT_OUTBOX); + AccountAuditOutboxRecord readback = copyAsPersistedRow(resultDsl, persisted); + refreshedRow.set(readback); + rows.add(readback); + return new MockResult[] {new MockResult(1, rows)}; + } throw new SQLException("Unexpected Account audit outbox query"); }; RecordListener recordListener = @@ -224,6 +225,12 @@ public void storeStart(RecordContext context) { LocalDateTime expectedUtc = LocalDateTime.ofInstant(envelope.occurredAt(), ZoneOffset.UTC); assertThat(storedOccurredAt.get()).isEqualTo(expectedUtc); assertThat(storedNextAttemptAt.get()).isEqualTo(expectedUtc); + assertThat(refreshedRow.get()).isNotNull(); + assertThat(refreshedRow.get().getOccurredAt()).isEqualTo(expectedUtc); + assertThat(refreshedRow.get().getNextAttemptAt()).isEqualTo(expectedUtc); + assertThat(persistedRow.get()).isNotNull(); + assertThat(persistedRow.get().getOccurredAt()).isEqualTo(expectedUtc); + assertThat(persistedRow.get().getNextAttemptAt()).isEqualTo(expectedUtc); } @Test @@ -260,6 +267,32 @@ private static void assertRejected( .hasMessage("Audit delivery state changed concurrently"); } + private static AccountAuditOutboxRecord copyAsPersistedRow( + DSLContext dsl, AccountAuditOutboxRecord source) { + AccountAuditOutboxRecord persisted = dsl.newRecord(ACCOUNT_AUDIT_OUTBOX); + persisted.setAuditEventId(source.getAuditEventId()); + persisted.setScope(source.getScope()); + persisted.setTenantId(source.getTenantId()); + persisted.setProducerService(source.getProducerService()); + persisted.setEventType(source.getEventType()); + persisted.setOccurredAt(source.getOccurredAt()); + persisted.setSchemaVersion(source.getSchemaVersion()); + persisted.setPayloadDigestVersion(source.getPayloadDigestVersion()); + persisted.setPayloadDigest(source.getPayloadDigest()); + persisted.setPayload(source.getPayload()); + persisted.setReceiverReceiptId(source.getReceiverReceiptId()); + persisted.setReceiverLogEventId(source.getReceiverLogEventId()); + persisted.setDeliveryStatus( + source.getDeliveryStatus() == null ? "PENDING" : source.getDeliveryStatus()); + persisted.setLastAttemptAt(source.getLastAttemptAt()); + persisted.setCreatedAt( + source.getCreatedAt() == null ? LocalDateTime.now(ZoneOffset.UTC) : source.getCreatedAt()); + persisted.setAttemptCount(source.getAttemptCount() == null ? 0 : source.getAttemptCount()); + persisted.setNextAttemptAt(source.getNextAttemptAt()); + persisted.setReceiverAuditProjectionVersion(source.getReceiverAuditProjectionVersion()); + return persisted; + } + private static AccountAuditOutboxRepository repositoryWithReadback( String status, String receiptId, String logEventId, boolean rowExists) { DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 6d21968179..c707796f94 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -700,6 +700,7 @@ void joinPublicProductionRejectsStillActiveBootstrapForIneligibleLifecycleState( AccountLifecycleState lifecycleState, String expectedCode) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -789,6 +790,7 @@ void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembership() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1030,6 +1032,7 @@ void scopeExpiringDuringFinalJoinEvaluationLeavesNewOrRetainedIntentPending( boolean retainedPendingIntent) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1127,6 +1130,7 @@ void scopeExpiringDuringFinalJoinEvaluationLeavesNewOrRetainedIntentPending( void joinPublicProductionRejectsLateAmbiguousPublicRealmBeforeMembershipCommit() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1249,6 +1253,7 @@ void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { void unboundFailedJoinReplaysOnlyAfterCurrentScopeAndAuthorityChecks() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1668,6 +1673,7 @@ void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredResult( String status, String outcome, boolean allowPublicJoin) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1750,6 +1756,7 @@ void expiredTerminalJoinScopeFailsClosedWithoutReplayingStoredResult( void newJoinRejectsExpiredConnectScopeBeforePersistingIntent() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -1897,6 +1904,7 @@ private AccountJoinOperationRepository.JoinOperation terminalJoinOperation( void joinPublicProductionHidesAnotherAccountsGlobalRequestIdEvidence(String originalStatus) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3199,6 +3207,7 @@ void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { void listBootstrapRealmsMapsZeroPublicAuthorityFromGameSession() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3222,6 +3231,7 @@ void listBootstrapRealmsMapsZeroPublicAuthorityFromGameSession() { void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3260,6 +3270,7 @@ void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { void listBootstrapRealmsRejectsMultipleVisiblePublicRealms() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3288,6 +3299,7 @@ void listBootstrapRealmsRejectsMultipleVisiblePublicRealms() { void listBootstrapRealmsAcceptsExactlyOneVisiblePublicRealm() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3326,6 +3338,7 @@ void bootstrapRealmDiscoveryAndDirectTextScopeIssuanceSuspendIncomingTransaction void listBootstrapRealmsDoesNotIssueScopeWhenPublicPointerBecomesPrivateBeforeFinalRead() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -3361,6 +3374,7 @@ void listBootstrapRealmsDoesNotIssueScopeWhenPublicPointerBecomesPrivateBeforeFi void listBootstrapRealmsDoesNotIssueScopeWhenPointerChangesDuringDiscovery() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -4971,6 +4985,7 @@ void issueConnectTokenClassifiesInactivePublicMembershipByJoinPolicy( String subscriptionStatus, String expectedCode) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5363,17 +5378,7 @@ void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); String connectScopeId = - retainedConnectScopeForTest( - 11L, - 7L, - REALM_ID, - "demo", - "production", - PLAYABLE_STATE_NAMESPACE_ID, - "SHARED", - 44L, - 23L, - 17L); + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); AuthenticationException exception = assertThrows( @@ -5435,6 +5440,7 @@ void listBootstrapCharactersClassifiesInactivePublicMembershipByJoinPolicy( String subscriptionStatus, String expectedCode) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5549,6 +5555,7 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterReachableDiscovery() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5791,6 +5798,7 @@ void listBootstrapRealmsRejectsNoncanonicalPlayableStateNamespaceIdFromReachable String namespaceId) { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5832,6 +5840,7 @@ void listBootstrapRealmsRejectsNoncanonicalPlayableStateNamespaceIdFromReachable void listBootstrapRealmsReadsFreshEntitlementsOncePerTenantPerInvocation() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5892,6 +5901,7 @@ void listBootstrapRealmsReadsFreshEntitlementsOncePerTenantPerInvocation() { void listBootstrapWorldsReadsFreshEntitlementsOncePerTenantPerInvocation() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -5941,6 +5951,7 @@ void listBootstrapWorldsReadsFreshEntitlementsOncePerTenantPerInvocation() { void listBootstrapWorldsOmitsCanceledTenantAndFailsWhenEntitlementIsUnavailable() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -6024,6 +6035,7 @@ void listBootstrapWorldsOmitsCanceledTenantAndFailsWhenEntitlementIsUnavailable( void listBootstrapRealmsPropagatesUnavailableEntitlements() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -6044,6 +6056,7 @@ void listBootstrapRealmsPropagatesUnavailableEntitlements() { void listBootstrapWorldsFailsInsteadOfReturningIncompleteWorldDiscovery() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -6097,6 +6110,7 @@ void listBootstrapWorldsFailsInsteadOfReturningIncompleteWorldDiscovery() { void listBootstrapRealmsRethrowsOtherAuthenticationErrors() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -6196,6 +6210,7 @@ void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { void listBootstrapRealmsRejectsRealmWithUnknownStateScope() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -7677,9 +7692,10 @@ private static RuntimeException unexpectedEntitlementFailure(String failureType) }; } - private static Account directTextAccount() { + private Account directTextAccount() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); return account; } @@ -7870,6 +7886,7 @@ private void verifyConnectTokenFailureDoesNotStoreSuccess( private CachedPublicConnectTokenReplay prepareCachedPublicConnectTokenReplay() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); @@ -7931,6 +7948,7 @@ private record PrivateConnectTokenContext(String bootstrapToken, String connectS private DirectTextJoinScope issueDirectTextConnectScopeForTest() { Account account = new Account(); account.setId(11L); + setPersistedAuthenticationIdentity(account); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); DirectTextCallerContext caller = new DirectTextCallerContext( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 93ca43318f..52bb5b0686 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -3223,10 +3223,8 @@ void playLeftMembershipRequiresJoinForPublicProduction() { assertThat(leftMembership.getGameplayAdmissionAllowed()).isFalse(); assertThat(leftMembership.getMembershipLifecycleState()).isEqualTo("INACTIVE"); assertThat(leftMembership.getAuthorityAvailability()).isEqualTo("AVAILABLE"); - assertThat(leftMembership.getAccountId()) - .isEqualTo("00000000-0000-0000-0000-000000000123"); - assertThat(leftMembership.getTenantId()) - .isEqualTo("00000000-0000-0000-0000-000000000022"); + assertThat(leftMembership.getAccountId()).isEqualTo("00000000-0000-0000-0000-000000000123"); + assertThat(leftMembership.getTenantId()).isEqualTo("00000000-0000-0000-0000-000000000022"); assertThat(leftMembership.getRequestAccountId()).isEqualTo("123"); assertThat(leftMembership.getRequestTenantId()).isEqualTo("22"); assertThat(leftMembership.getMembershipVersionMap()) @@ -3479,11 +3477,11 @@ void contradictoryLeftEventEvidenceCannotAdmitGameplay(String defect) { assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); assertThat(result.outputs()).hasSize(1); assertThat(result.outputs().get(0).payload()).isInstanceOf(ErrorOutput.class); assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) - .isEqualTo("error.play.world-access-denied"); + .isEqualTo("error.play.authority-unavailable"); Mockito.verifyNoInteractions( entityManagementClient, sessionContextService, From eb556c1c4b4b6ca1f2d20a9a870316cd7639e349 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 06:43:49 +1300 Subject: [PATCH 20/23] Bind retained membership fixtures to exact persisted UUID scopes --- .../AccountAuditOutboxRepositoryTest.java | 3 +- .../service/impl/AccountServiceImplTest.java | 48 +++++++++++++++++-- 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java index 6e2dc1c782..17d9160275 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java @@ -287,7 +287,8 @@ private static AccountAuditOutboxRecord copyAsPersistedRow( persisted.setLastAttemptAt(source.getLastAttemptAt()); persisted.setCreatedAt( source.getCreatedAt() == null ? LocalDateTime.now(ZoneOffset.UTC) : source.getCreatedAt()); - persisted.setAttemptCount(source.getAttemptCount() == null ? 0 : source.getAttemptCount()); + persisted.setAttemptCount( + source.getAttemptCount() == null ? Integer.valueOf(0) : source.getAttemptCount()); persisted.setNextAttemptAt(source.getNextAttemptAt()); persisted.setReceiverAuditProjectionVersion(source.getReceiverAuditProjectionVersion()); return persisted; diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index c707796f94..d25519b4f3 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -5007,7 +5007,7 @@ void issueConnectTokenClassifiesInactivePublicMembershipByJoinPolicy( // with a valid signed scope retained from an earlier eligible snapshot. String connectScopeId = retainedConnectScopeForTest( - 11L, + account, 7L, REALM_ID, "demo", @@ -5363,8 +5363,9 @@ void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( if (membershipExists) { AccountTenantMembership nonAdmittingMembership = membership(account, 7L); nonAdmittingMembership.setGameplayAdmissionAllowed(false); + AccountTenantMembership admittingMembership = membership(account, 7L); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(nonAdmittingMembership)); + .thenReturn(Optional.of(admittingMembership), Optional.of(nonAdmittingMembership)); } else { when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) .thenReturn(Optional.empty()); @@ -5462,7 +5463,7 @@ void listBootstrapCharactersClassifiesInactivePublicMembershipByJoinPolicy( // with a valid signed scope retained from an earlier eligible snapshot. String connectScopeId = retainedConnectScopeForTest( - 11L, + account, 7L, REALM_ID, "demo", @@ -5606,7 +5607,7 @@ void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDis // private. A missing membership must not inherit public JOIN behavior from the slug. String connectScopeId = retainedConnectScopeForTest( - 11L, + account, 7L, REALM_ID, "demo", @@ -7769,6 +7770,45 @@ private String retainedConnectScopeForTest( Map.entry("connectScopeExpiresAt", expiresAt.toString()))); } + private String retainedConnectScopeForTest( + Account account, + long tenantId, + String realmId, + String worldSlug, + String realmSlug, + String playableStateNamespaceId, + String playableStateScope, + long gameInstanceId, + long catalogRevision, + long pointerVersion) { + UUID accountUuid = account.getAccountUuid(); + if (accountUuid == null + || !java.util.Objects.equals(account.getId(), account.getAccountUuidSourceNumericId())) { + throw new IllegalArgumentException("Account fixture lacks a persisted UUID identity"); + } + java.time.Instant evaluatedAt = java.time.Instant.now(); + java.time.Instant expiresAt = + evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); + return new JwtUtil(JWT_SECRET, 30000L) + .generateToken( + accountUuid.toString(), + tokenProperties.getConnectScopeExpirationMs(), + Map.ofEntries( + Map.entry("aud", "bootstrap-connect-scope"), + Map.entry("accountId", accountUuid.toString()), + Map.entry("tenantId", tenantId), + Map.entry("realmId", realmId), + Map.entry("worldSlug", worldSlug), + Map.entry("realmSlug", realmSlug), + Map.entry("playableStateNamespaceId", playableStateNamespaceId), + Map.entry("playableStateScope", playableStateScope), + Map.entry("gameInstanceId", gameInstanceId), + Map.entry("catalogRevision", catalogRevision), + Map.entry("pointerVersion", pointerVersion), + Map.entry("evaluatedAt", evaluatedAt.toString()), + Map.entry("connectScopeExpiresAt", expiresAt.toString()))); + } + private PrivateConnectTokenContext preparePrivateConnectTokenContext( Account account, boolean grantAtIssuance) { return preparePrivateConnectTokenContext(account, grantAtIssuance, "ACTIVE"); From 699a25e022c9224d24b7a491ee4ab1d4a67f22f2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 06:49:06 +1300 Subject: [PATCH 21/23] Remove unused numeric scope fixture after UUID convergence --- .../service/impl/AccountServiceImplTest.java | 34 ------------------- 1 file changed, 34 deletions(-) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index d25519b4f3..00101d3c08 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -7736,40 +7736,6 @@ private static String hash(String password) { } } - private String retainedConnectScopeForTest( - long accountId, - long tenantId, - String realmId, - String worldSlug, - String realmSlug, - String playableStateNamespaceId, - String playableStateScope, - long gameInstanceId, - long catalogRevision, - long pointerVersion) { - java.time.Instant evaluatedAt = java.time.Instant.now(); - java.time.Instant expiresAt = - evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); - return new JwtUtil(JWT_SECRET, 30000L) - .generateToken( - Long.toString(accountId), - tokenProperties.getConnectScopeExpirationMs(), - Map.ofEntries( - Map.entry("aud", "bootstrap-connect-scope"), - Map.entry("accountId", accountId), - Map.entry("tenantId", tenantId), - Map.entry("realmId", realmId), - Map.entry("worldSlug", worldSlug), - Map.entry("realmSlug", realmSlug), - Map.entry("playableStateNamespaceId", playableStateNamespaceId), - Map.entry("playableStateScope", playableStateScope), - Map.entry("gameInstanceId", gameInstanceId), - Map.entry("catalogRevision", catalogRevision), - Map.entry("pointerVersion", pointerVersion), - Map.entry("evaluatedAt", evaluatedAt.toString()), - Map.entry("connectScopeExpiresAt", expiresAt.toString()))); - } - private String retainedConnectScopeForTest( Account account, long tenantId, From e65b854895d76cd33cef2ecbd9d60731a96c7993 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:23:49 +1300 Subject: [PATCH 22/23] Allow Validation for stacked pull requests --- .github/workflows/ci.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a73a43b834..7ea8ae548d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [ main, develop ] pull_request: - branches: [ main, develop ] types: [opened, synchronize, reopened, edited] workflow_dispatch: From 8c45206955a218d41dc0aeb6f256ca24454e0f9b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:34:54 +1300 Subject: [PATCH 23/23] Carry forward reviewed CI safety corrections --- .github/workflows/ci.yml | 2 +- .../workflows/publish-pr-runtime-images.yml | 4 +- .github/workflows/security.yml | 3 +- .github/workflows/smoke.yml | 51 +++++++++++- .github/workflows/static-analysis-summary.yml | 3 +- .../preview/resolve-preview-image-tag.sh | 2 +- .../tests/ci-validation-summary-contract.sh | 12 +++ .../pr-required-gate-context-contract.sh | 83 +++++++++++++++++++ .../tests/pr-retarget-workflow-contract.sh | 79 +++++++++++++++++- .../pr-runtime-image-publication-contract.sh | 29 ++++++- dev-tools/tests/security-summary-contract.sh | 51 ++++++++++++ .../tests/static-analysis-summary-contract.sh | 11 ++- 12 files changed, 314 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7ea8ae548d..7218558e53 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1240,7 +1240,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) {