diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0d22d58466..34a02f2b73 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1008,6 +1008,20 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepositoryIntegrationTest#concurrentDuplicateCreationRequestsConvergeOnOneUuidAndReceipt()' \ game-design-service + - name: Verify Account fresh UUID pair and snapshot PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepositoryIntegrationTest \ + --require-suite net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepositoryIntegrationTest#v39PreservesRetainedPairHistoryAndEnforcesUuidOnlyFreshRows()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepositoryIntegrationTest#v39RefusesToRewriteAnExistingFreshNumericPair()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#freshUuidSnapshotEnrollsExactNonAdmittingBaselineAndRetriesWithoutSideEffects()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#freshUuidSnapshotRejectsAdvancedTenantGenerationAndRollsBackBaselineWrites()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#concurrentFreshUuidSnapshotCallsInitializeOneExactPairBaseline()' \ + account-service + - name: ๐Ÿ”Ž Verify Game Session PostgreSQL proof case if: ${{ matrix.module == 'game-session-service' }} run: | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 1a145ed8ec..fa8d46a4a2 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -18,7 +18,9 @@ Account V29 keeps the numeric `accounts.id` primary key and adds an immutable ca 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 selected 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 exact 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 must reject conflicts regardless of which evidence path arrives first. Only after exact source readback may Account commit the association and invoke existing tenant-generation initialization without resetting existing state. This #2915 implementation is in progress and has no passing focused consumer/transaction/readback proof; the strict producer/readback database suite failed as recorded in the tracker. It creates no numeric Account tenant alias or selector and does not enroll membership or enable any 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). +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 exact 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. Only after exact source readback may Account commit the association and invoke existing tenant-generation initialization without resetting existing state. 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). + +The V39 candidate extends the existing pair authority table for that UUID-only association: a fresh pair has no legacy numeric tenant key, while an approved retained pair keeps its positive one-to-one bridge unchanged. Contradictory preexisting fresh numeric keys abort migration without reinterpretation or deletion. A fenced fresh-UUID producer reads back the exact immutable association and constructs the existing complete, nonadmitting never-joined snapshot from its positive pair baseline and pristine upstream authority. It does not create membership or event history, support fresh positive JOIN, reset progressed authority, or enable the runtime RPC; canonical request propagation, advanced source-event support and their producer/consumer proof remain open in the tracker. 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. @@ -193,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 generated proto and Account producer emit `membershipLifecycleState` and `membershipAuthorityGeneration`. Game Session `PLAY` validates lifecycle consistency against `membershipExists`, `gameplayAdmissionAllowed`, and `membershipVersion`, and rejects a missing or nonpositive generation. It does not validate `authorityAvailability`, roles, the complete tuple, or outbox checkpoints; those fields are absent from the current response. The live Account RPC still rejects before data access, so mocked consumer checks do not establish a fresh atomic target snapshot or fail-closed proof over its complete evidence bundle. +- `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). - `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 e111cd6cb8..a46edc7d71 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -169,3 +169,8 @@ Entry format: - Context: the complete Account snapshot/first-JOIN test held the Account row `FOR UPDATE` and waited for JOIN's explicit Account-lock spy. JOIN first inserts its PENDING intent, whose foreign-key check can already wait on that same row. - Observation: exact CI timed out at the later spy, not at a source invariant. Instrumenting the actual intent-insert backend before the real insert retained the exact `pg_blocking_pids` correlation and complete before/after DTO assertions; corrected CI `36778631119` executed the race once successfully. Worker exceptions are surfaced rather than hidden behind a latch timeout. - Expected pattern: trace earlier foreign-key and deferred-trigger work before selecting a concurrency signal; prove the exact blocked backend/owner relation and do not fix a misplaced signal by extending timeouts or changing production transaction order. + +- `2026-10-01`: Consume the final validation result before committing a claimed green checkpoint + - 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. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index f479b029c9..8c71fec498 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) โ†’ [#2881](https://github.com/benhook1013/FireMUD/pull/2881) โ†’ [#2911](https://github.com/benhook1013/FireMUD/pull/2911) โ†’ [#2914](https://github.com/benhook1013/FireMUD/pull/2914) โ†’ [#2915](https://github.com/benhook1013/FireMUD/pull/2915) | Provisional; #2915's Account fresh-tenant consumer is in progress, but its strict creation database gate failed all seven executed cases after migration; no passing producer/readback or live consumer proof is claimed. Account authority/evidence, credential/delegation/registry, fresh UUID association, protected ring delivery, durable reconnect, and HTTPS/mail/abuse/browser gates remain open. Membership RPC and credentials stay denied; ring mount unpublished. See the [Player Access tracker](../implementation-tracking/player-access-and-session.md) for 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) โ†’ [#2881](https://github.com/benhook1013/FireMUD/pull/2881) โ†’ [#2911](https://github.com/benhook1013/FireMUD/pull/2911) โ†’ [#2914](https://github.com/benhook1013/FireMUD/pull/2914) โ†’ [#2915](https://github.com/benhook1013/FireMUD/pull/2915) | Provisional; #2915's corrected creation and Account association database proof passed, but complete authenticated snapshot, current authority, credential/delegation/registry, protected ring delivery, durable reconnect, and HTTPS/mail/abuse/browser gates remain open. Database component proof is not a live owner handoff or activation proof. Membership RPC and credentials 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 | โ€” | โ€” | 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 163aa157e0..041dbec621 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 +PR #2917's snapshot failure-injection fixture now stubs the underlying Mockito target instead of entering the Spring transaction proxy during setup. The actual producer call still traverses that original proxy inside its owner transaction and executes the real mutation before the injected failure; neither `MANDATORY` propagation nor the explicit repository guard is weakened. The correction's local Account full check/JAR, formatting and static analysis passed, with unchanged 426 unit results up-to-date and all 123 PostgreSQL cases skipped without Docker. Documentation validation is rerun after the final status edit. Corrected runtime execution of both failed cases remains required; the failed exact-head CI below is incident evidence, not replaced by local skips. + +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 with zero skips, failures or errors; every strictly required retry/concurrency/rollback case executed once. These counts come from the strict JUnit XML-verifier logs, not JaCoCo; retained artifacts contain HTML but not raw JUnit XML. Account, Game Design and shared-core unit tasks ran with build/configuration caches disabled. Account's check and JAR passed; Game Design's check failed on the unchanged Entity baseline-migration fixture already routed to #2872 and its hosted JAR step skipped. Automation formatting, shared Ruff and the dev-demo summary validator also keep aggregate CI red. This supersedes the earlier failed creation-fixture proof below, not its incident evidence. Database component proof does not establish live mTLS/SPIFFE, certificate rotation, fresh-image boot, a deployed cross-owner handoff or activation. + +Draft [#2917](https://github.com/benhook1013/FireMUD/pull/2917) extends the existing V36 pair/snapshot authority through additive V39 rather than adding a parallel authority or numeric alias. Fresh provenance requires a null legacy tenant key; approved retained provenance keeps its positive key, one-to-one constraint and exact counters/history. Migration rejects any contradictory preexisting fresh numeric pair without rewriting or deleting it. The owner-fenced producer accepts canonical Account and fresh tenant UUIDs, re-reads the V38 association/claim and positive pair baseline, and assembles the existing complete event-free nonadmitting snapshot. It acquires upstream generation locks in composite order and never resets advanced generations or previously committed history. Local Account full check/JAR passed with 426 executed unit cases; 123 PostgreSQL cases skipped without Docker. [CI 36800321082](https://github.com/benhook1013/FireMUD/actions/runs/36800321082) on `023fcca557278efab398ecaba4f51262847cff17` executed all eight pair/migration cases successfully and all eight UUID-snapshot cases with zero skips but two fixture failures. Named enrollment/retry, advanced-generation rollback and actual concurrent Account-fence wait cases passed; the entire snapshot suite did not. Failure injection stubs a Spring `MANDATORY` proxy outside a transaction, raising `IllegalTransactionStateException` and leaving unfinished Mockito state that affects the provenance-negative case. A fixture-only correction must preserve the real production proxy/transaction and prove both cases before scoped completion; counts are from strict XML-verifier logs, diagnoses from HTML, not uploaded raw XML. Aggregate CI is red on these failures and separately owned Automation, Game Design, Ruff and dev-demo validator failures. No positive fresh JOIN, canonical Game Session request path, authenticated runtime response, credential producer or ring mount is enabled; Unit 1B remains provisional. + The next Account-owned committed-connect source reader is an unwired prerequisite, not an authorization or credential producer. It recovers a complete successful V35 receipt and purpose-bound envelope by exact identity, checks the original compact JWT hash/JTI and asymmetric signature against the closed selected-target profile, verifies the Gateway assertion independently, and proves source/context correspondence under the Account row fence and approved retained tenant mapping. It requires the exact Game Session peer and an active owner transaction before data access, returns no raw credential, and rechecks unchanged deadlines after a fence wait. The consolidated local Account check passed with 413 unit cases executed, including 11 original-source verifier and four early-denial cases; all 105 PostgreSQL cases compiled but skipped without Docker, including the seven source-readback cases. Separately, exact #2914 head `ac8d52758384e16a2c5f1fc086af40589ad86350` [CI 36785132585](https://github.com/benhook1013/FireMUD/actions/runs/36785132585) passed its Account and Game Session jobs: the seven new PostgreSQL cases and exact-reread/fence-expiry methods each executed once with zero skips or failures, alongside the strict 30 JOIN, 9 connect-issuance, 9 bare-LOGIN storage, 2 authority-generation, 4 authority-outbox, 25 Script Pin, and 16 WebSocket cases. Aggregate CI remains red on failures outside this slice. The source reader supplies original-source evidence onlyโ€”not current authority or authorizationโ€”and does not supply fresh tenant authority, an issued-token registry, protected key delivery, or a working bare-LOGIN exchange; no runtime path or mount is enabled. Exact #2911 `78c3fe88614708a4cd224800ac0f1bd6d03b310e` [CI 36778631119](https://github.com/benhook1013/FireMUD/actions/runs/36778631119) passed both strict Account PostgreSQL gates: JOIN 30/30, connect issuance 9/9, bare-LOGIN storage 9/9, authority-generation 2/2 and authority-outbox 4/4, all zero skips/failures. The complete nonadmitting snapshot versus concurrent first-JOIN case and both exhaustion rollback methods each executed once. Game Session strict Script Pin 25/25 and WebSocket 16/16 also passed. Account and Game Session checks disabled build/configuration cache and executed their tasks; aggregate CI remains red on separately routed shared tooling, Game Design fixture and Automation formatting failures. This closes those source/component database-proof gaps, not the live authenticated snapshot, complete immutable Account evidence bundle, credential producer/registry, or end-to-end bare-LOGIN gates below. The runtime RPC and credential paths remain denied, and the ring mount remains unpublished. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java index 0c6b377335..5e156a70ee 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java @@ -10,6 +10,7 @@ import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Stores the durable Account-owned authority state for one verified Account/tenant pair. @@ -47,6 +48,7 @@ public AccountMembershipPairAuthorityRepository(DSLContext dsl) { @Transactional(propagation = Propagation.MANDATORY) public PairAuthority enrollAbsence( UUID accountUuid, UUID tenantUuid, VerifiedTenantProvenance provenance) { + requireOwnerTransaction(); requireScope(accountUuid, tenantUuid); Objects.requireNonNull(provenance, "verified tenant provenance is required"); @@ -75,7 +77,7 @@ public PairAuthority enrollAbsence( Optional readback = readForUpdate(accountUuid, tenantUuid); if (readback.isEmpty()) { - if (readByLegacyScopeForUpdate(accountUuid, provenance.legacyTenantId()).isPresent()) { + if (hasRetainedLegacyScopeCollision(accountUuid, provenance)) { throw new IllegalStateException( "Verified Account tenant association conflicts with an existing pair authority"); } @@ -106,6 +108,7 @@ public PairAuthority enrollProvenPositive( UUID tenantUuid, VerifiedTenantProvenance provenance, ProvenPositiveCheckpoint checkpoint) { + requireOwnerTransaction(); requireScope(accountUuid, tenantUuid); Objects.requireNonNull(provenance, "verified tenant provenance is required"); Objects.requireNonNull(checkpoint, "verified positive membership checkpoint is required"); @@ -154,7 +157,7 @@ public PairAuthority enrollProvenPositive( Optional readback = readForUpdate(accountUuid, tenantUuid); if (readback.isEmpty()) { - if (readByLegacyScopeForUpdate(accountUuid, provenance.legacyTenantId()).isPresent()) { + if (hasRetainedLegacyScopeCollision(accountUuid, provenance)) { throw new IllegalStateException( "Verified Account tenant association conflicts with an existing pair authority"); } @@ -174,6 +177,7 @@ public PairAuthority enrollProvenPositive( */ @Transactional(propagation = Propagation.MANDATORY) public Optional readForUpdate(UUID accountUuid, UUID tenantUuid) { + requireOwnerTransaction(); requireScope(accountUuid, tenantUuid); Record row = dsl.fetchOne( @@ -198,6 +202,7 @@ public Optional readForUpdate(UUID accountUuid, UUID tenantUuid) */ @Transactional(propagation = Propagation.MANDATORY) public PairAuthority commitTransition(PairAuthority expected, PairTransition transition) { + requireOwnerTransaction(); Objects.requireNonNull(expected, "expected pair authority is required"); Objects.requireNonNull(transition, "pair authority transition is required"); long nextVersion = increment(expected.membershipVersion(), "membership version"); @@ -229,7 +234,8 @@ public PairAuthority commitTransition(PairAuthority expected, PairTransition tra + " SET membership_exists = ?, membership_version = ?, " + "membership_authority_generation = ?, last_event_sequence = ?, " + "last_event_id = ?, last_event_digest = ?, last_transition_invalidated = ? " - + "WHERE account_uuid = ? AND tenant_uuid = ? AND legacy_tenant_id = ? " + + "WHERE account_uuid = ? AND tenant_uuid = ? " + + "AND legacy_tenant_id IS NOT DISTINCT FROM ? " + "AND tenant_provenance_kind = ? AND tenant_source_operation_id = ? " + "AND tenant_provenance_digest = ? AND membership_exists = ? " + "AND membership_version = ? AND membership_authority_generation = ? " @@ -286,7 +292,7 @@ public PairAuthority commitTransition(PairAuthority expected, PairTransition tra } private Optional readByLegacyScopeForUpdate( - UUID accountUuid, long legacyTenantId) { + UUID accountUuid, Long legacyTenantId) { Record row = dsl.fetchOne( "SELECT " @@ -300,6 +306,12 @@ private Optional readByLegacyScopeForUpdate( return Optional.ofNullable(row).map(this::mapRow); } + private boolean hasRetainedLegacyScopeCollision( + UUID accountUuid, VerifiedTenantProvenance provenance) { + return provenance.kind() == TenantProvenanceKind.APPROVED_RETAINED + && readByLegacyScopeForUpdate(accountUuid, provenance.legacyTenantId()).isPresent(); + } + private PairAuthority mapRow(Record row) { try { return new PairAuthority( @@ -338,6 +350,13 @@ private void requireScope(UUID accountUuid, UUID tenantUuid) { } } + private void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account membership pair authority access requires an active owner transaction"); + } + } + private long increment(long value, String label) { try { return Math.addExact(value, 1L); @@ -359,11 +378,20 @@ public enum TenantProvenanceKind { /** Immutable verified tenant-association facts supplied by the caller. */ public record VerifiedTenantProvenance( - long legacyTenantId, TenantProvenanceKind kind, UUID sourceOperationId, String digest) { + Long legacyTenantId, TenantProvenanceKind kind, UUID sourceOperationId, String digest) { public VerifiedTenantProvenance { - if (legacyTenantId <= 0L || kind == null || sourceOperationId == null) { + if (kind == null || sourceOperationId == null) { throw new IllegalArgumentException("Verified Account tenant provenance is incomplete"); } + if (kind == TenantProvenanceKind.APPROVED_RETAINED + && (legacyTenantId == null || legacyTenantId <= 0L)) { + throw new IllegalArgumentException( + "Approved retained tenant provenance requires a positive legacy tenant ID"); + } + if (kind == TenantProvenanceKind.FRESH_GAME_DESIGN && legacyTenantId != null) { + throw new IllegalArgumentException( + "Fresh Game Design tenant provenance must not carry a legacy tenant ID"); + } requireDigest(digest, "Tenant provenance digest"); } } 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 32aac78520..8e7a64ed63 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 @@ -41,15 +41,18 @@ 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.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Produces the Account-owned V33 authority event for an explicit public-production JOIN. */ +/** Coordinates Account-owned membership authority events and fenced snapshot evidence. */ @Service @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -64,6 +67,7 @@ public class AccountMembershipAuthorityEventProducer { private final AccountMembershipPairAuthorityRepository pairAuthorityRepository; private final AccountRepository accountRepository; private final AccountTenantIdentityResolver tenantIdentityResolver; + private final FreshTenantIdentityAssociationRepository freshTenantIdentityAssociationRepository; private final AccountAuthorityGenerationRepository authorityGenerationRepository; private final AccountAuthorityOutboxRepository authorityOutboxRepository; private final AccountMembershipTransitionReceiptRepository transitionReceiptRepository; @@ -75,6 +79,7 @@ public AccountMembershipAuthorityEventProducer( AccountMembershipPairAuthorityRepository pairAuthorityRepository, AccountRepository accountRepository, AccountTenantIdentityResolver tenantIdentityResolver, + FreshTenantIdentityAssociationRepository freshTenantIdentityAssociationRepository, AccountAuthorityGenerationRepository authorityGenerationRepository, AccountAuthorityOutboxRepository authorityOutboxRepository, AccountMembershipTransitionReceiptRepository transitionReceiptRepository, @@ -84,6 +89,7 @@ public AccountMembershipAuthorityEventProducer( this.pairAuthorityRepository = pairAuthorityRepository; this.accountRepository = accountRepository; this.tenantIdentityResolver = tenantIdentityResolver; + this.freshTenantIdentityAssociationRepository = freshTenantIdentityAssociationRepository; this.authorityGenerationRepository = authorityGenerationRepository; this.authorityOutboxRepository = authorityOutboxRepository; this.transitionReceiptRepository = transitionReceiptRepository; @@ -379,19 +385,114 @@ public NeverJoinedMembershipSnapshot readNeverJoinedMembershipSnapshot( throw new IllegalStateException("Never-joined Account membership row is not absent"); } transitionReceiptRepository.assertNewMembershipTransitionCanStart(accountId, legacyTenantId); + return assembleNeverJoinedMembershipSnapshot( + identity.accountUuid(), identity.tenantUuid(), verifiedProvenance(identity)); + } + + /** + * Enrolls and reads the non-admitting baseline for one exact Game Design-issued tenant UUID. + * + *

The Account row is the transaction fence. The UUID-to-UUID fresh association is read only + * after that row is locked and reread, and no numeric tenant selector or alias is accepted or + * derived. This prepares local authority evidence only; it does not create membership, an event, + * a credential, or an enabled runtime RPC. + */ + @Transactional(propagation = Propagation.MANDATORY) + public NeverJoinedMembershipSnapshot readFreshNeverJoinedMembershipSnapshot( + UUID accountUuid, UUID tenantUuid) { + requireActiveOwnerTransaction(); + requireCanonicalUuidInput(accountUuid, "Account UUID"); + requireCanonicalUuidInput(tenantUuid, "tenant UUID"); + + Account initialAccount = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow(() -> new IllegalStateException("Fresh snapshot Account row is absent")); + requirePersistedAccountIdentity(initialAccount, accountUuid); + long accountId = initialAccount.getId(); + + // Preserve the JOIN lock order: acquire the numeric Account-row lock before consulting tenant + // provenance, pair authority, or any membership-snapshot input. + joinOperationRepository.lockAccount(accountId); + Account fencedAccount = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow( + () -> new IllegalStateException("Fresh snapshot Account row disappeared at fence")); + requirePersistedAccountIdentity(fencedAccount, accountUuid); + if (!Objects.equals(initialAccount.getId(), fencedAccount.getId()) + || initialAccount.getAccountUuidProvenance() != fencedAccount.getAccountUuidProvenance() + || !Objects.equals( + initialAccount.getAccountUuidSourceNumericId(), + fencedAccount.getAccountUuidSourceNumericId())) { + throw new IllegalStateException("Fresh snapshot Account identity changed at its row fence"); + } + + FreshTenantCreationEvidence evidence = + freshTenantIdentityAssociationRepository + .read(tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Fresh Game Design tenant association is absent")); + if (!tenantUuid.equals(evidence.canonicalTenantId())) { + throw new IllegalStateException( + "Fresh Game Design tenant association differs from its canonical UUID scope"); + } + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + evidence.operationId(), + evidence.evidenceDigest()); + + // Take upstream generation/fence locks in the composite reader's canonical order before the + // membership initializer takes its Account/tenant locks. The Account entity row remains the + // outer owner fence, and the full composite snapshot is reread below after enrollment. + CompositeSnapshot upstream = lockUpstreamAuthorityScopes(accountUuid, tenantUuid); + requireFreshUpstreamSequenceZeroBaseline(accountUuid, tenantUuid, upstream); + + String membershipStreamKey = membershipStreamKey(accountUuid, tenantUuid); + Optional existingPair = + pairAuthorityRepository.readForUpdate(accountUuid, tenantUuid); + if (existingPair.isEmpty()) { + if (authorityOutboxRepository.readCheckpoint(membershipStreamKey).isPresent()) { + throw new IllegalStateException( + "Absent fresh Account membership has retained authority-event history"); + } + ScopeState generation = + authorityGenerationRepository.initialize( + AuthorityScope.membership(accountUuid, tenantUuid)); + if (generation.generation() != 1L || generation.sourceVersion() != 1L) { + throw new IllegalStateException( + "Fresh never-joined Account membership generation did not initialize at one"); + } + } + + PairAuthority pair = pairAuthorityRepository.enrollAbsence(accountUuid, tenantUuid, provenance); + if (!provenance.equals(pair.provenance()) + || pair.membershipExists() + || pair.membershipVersion() != 1L + || pair.lastEventSequence() != 0L) { + throw new IllegalStateException( + "Fresh never-joined Account membership differs from its positive pair baseline"); + } + return assembleNeverJoinedMembershipSnapshot(accountUuid, tenantUuid, provenance); + } + + private NeverJoinedMembershipSnapshot assembleNeverJoinedMembershipSnapshot( + UUID accountUuid, UUID tenantUuid, VerifiedTenantProvenance provenance) { PairAuthority pair = pairAuthorityRepository - .readForUpdate(identity.accountUuid(), identity.tenantUuid()) + .readForUpdate(accountUuid, tenantUuid) .orElseThrow(() -> new IllegalStateException("Never-joined pair baseline is absent")); - CompositeSnapshot authority = readSnapshot(identity); + CompositeSnapshot authority = readSnapshot(accountUuid, tenantUuid); ScopeState member = only(authority.memberships(), "membership"); - requireMatchingFence(authority, member, identity.accountUuid()); + requireMatchingFence(authority, member, accountUuid); List upstreamCheckpoints = - readBaselineUpstreamCheckpoints(identity, authority); - String streamKey = membershipStreamKey(identity); + readBaselineUpstreamCheckpoints(accountUuid, tenantUuid, authority); + String streamKey = membershipStreamKey(accountUuid, tenantUuid); OutboxCheckpointEntry membershipCheckpoint = requireSequenceZeroCheckpoint(streamKey, member, "membership"); - if (!verifiedProvenance(identity).equals(pair.provenance()) + if (!provenance.equals(pair.provenance()) || pair.membershipExists() || pair.lastEventSequence() != 0L || pair.membershipVersion() != 1L @@ -404,9 +505,8 @@ public NeverJoinedMembershipSnapshot readNeverJoinedMembershipSnapshot( decimal(authority.issuer().generation()), decimal(authority.account().generation()), Map.of( - identity.tenantUuid().toString(), - decimal(only(authority.tenants(), "tenant").generation())), - Map.of(identity.tenantUuid().toString(), decimal(member.generation())), + tenantUuid.toString(), decimal(only(authority.tenants(), "tenant").generation())), + Map.of(tenantUuid.toString(), decimal(member.generation())), List.of(), Optional.empty(), Optional.empty()); @@ -414,9 +514,9 @@ public NeverJoinedMembershipSnapshot readNeverJoinedMembershipSnapshot( checkpoints.add(membershipCheckpoint); checkpoints = orderedCheckpoints(checkpoints); return new NeverJoinedMembershipSnapshot( - identity.accountUuid().toString(), - identity.tenantUuid().toString(), - Map.of(identity.tenantUuid().toString(), decimal(pair.membershipVersion())), + accountUuid.toString(), + tenantUuid.toString(), + Map.of(tenantUuid.toString(), decimal(pair.membershipVersion())), decimal(pair.membershipAuthorityGeneration()), tuple, decimal(authority.issuanceFence().value()), @@ -426,6 +526,29 @@ public NeverJoinedMembershipSnapshot readNeverJoinedMembershipSnapshot( List.of()); } + private void requireFreshUpstreamSequenceZeroBaseline( + UUID accountUuid, UUID tenantUuid, CompositeSnapshot snapshot) { + ScopeState tenant = only(snapshot.tenants(), "tenant"); + if (!AuthorityScope.issuer(AccountServiceImpl.ACCOUNT_JWT_ISSUER) + .equals(snapshot.issuer().scope()) + || !AuthorityScope.account(accountUuid).equals(snapshot.account().scope()) + || !AuthorityScope.tenant(tenantUuid).equals(tenant.scope()) + || !snapshot.memberships().isEmpty() + || !accountUuid.equals(snapshot.issuanceFence().accountId()) + || !snapshot.issuanceFence().equals(snapshot.account().issuanceFence())) { + throw new IllegalStateException( + "Fresh Account authority snapshot does not cover its exact issuer/account/tenant scopes"); + } + requireSequenceZeroCheckpoint(accountStreamKey(accountUuid), snapshot.account(), "account"); + requireSequenceZeroCheckpoint(issuerStreamKey(), snapshot.issuer(), "issuer"); + requireSequenceZeroCheckpoint(tenantStreamKey(tenantUuid), tenant, "tenant"); + } + + private CompositeSnapshot lockUpstreamAuthorityScopes(UUID accountUuid, UUID tenantUuid) { + return authorityGenerationRepository.readCompositeSnapshot( + AccountServiceImpl.ACCOUNT_JWT_ISSUER, accountUuid, List.of(tenantUuid), List.of()); + } + /** * Establishes a committed never-joined baseline before a separate JOIN transaction may consume * it. A retained active row is enrolled only from its exact current positive event/receipt proof; @@ -441,6 +564,7 @@ public void preparePairAuthorityForJoin(long accountId, long legacyTenantId) { return; } + lockUpstreamAuthorityScopes(identity.accountUuid(), identity.tenantUuid()); transitionReceiptRepository.assertNewMembershipTransitionCanStart(accountId, legacyTenantId); if (authorityOutboxRepository.readCheckpoint(membershipStreamKey(identity)).isPresent()) { throw new IllegalStateException( @@ -1109,12 +1233,17 @@ private static int compareUnsignedUtf8(String left, String right) { private List readBaselineUpstreamCheckpoints( Identity identity, CompositeSnapshot snapshot) { + return readBaselineUpstreamCheckpoints(identity.accountUuid(), identity.tenantUuid(), snapshot); + } + + private List readBaselineUpstreamCheckpoints( + UUID accountUuid, UUID tenantUuid, CompositeSnapshot snapshot) { ScopeState tenant = only(snapshot.tenants(), "tenant"); if (!AuthorityScope.issuer(AccountServiceImpl.ACCOUNT_JWT_ISSUER) .equals(snapshot.issuer().scope()) - || !AuthorityScope.account(identity.accountUuid()).equals(snapshot.account().scope()) - || !AuthorityScope.tenant(identity.tenantUuid()).equals(tenant.scope()) - || !AuthorityScope.membership(identity.accountUuid(), identity.tenantUuid()) + || !AuthorityScope.account(accountUuid).equals(snapshot.account().scope()) + || !AuthorityScope.tenant(tenantUuid).equals(tenant.scope()) + || !AuthorityScope.membership(accountUuid, tenantUuid) .equals(only(snapshot.memberships(), "membership").scope())) { throw new IllegalStateException( "Account authority snapshot does not cover the exact issuer/account/tenant scopes"); @@ -1123,10 +1252,9 @@ private List readBaselineUpstreamCheckpoints( return orderedCheckpoints( List.of( requireSequenceZeroCheckpoint( - accountStreamKey(identity.accountUuid()), snapshot.account(), "account"), + accountStreamKey(accountUuid), snapshot.account(), "account"), requireSequenceZeroCheckpoint(issuerStreamKey(), snapshot.issuer(), "issuer"), - requireSequenceZeroCheckpoint( - tenantStreamKey(identity.tenantUuid()), tenant, "tenant"))); + requireSequenceZeroCheckpoint(tenantStreamKey(tenantUuid), tenant, "tenant"))); } private OutboxCheckpointEntry requireSequenceZeroCheckpoint( @@ -1199,11 +1327,15 @@ private RoleSnapshot requireRoleSnapshot(Identity identity, AccountTenantMembers } private CompositeSnapshot readSnapshot(Identity identity) { + return readSnapshot(identity.accountUuid(), identity.tenantUuid()); + } + + private CompositeSnapshot readSnapshot(UUID accountUuid, UUID tenantUuid) { return authorityGenerationRepository.readCompositeSnapshot( AccountServiceImpl.ACCOUNT_JWT_ISSUER, - identity.accountUuid(), - List.of(identity.tenantUuid()), - List.of(identity.tenantUuid())); + accountUuid, + List.of(tenantUuid), + List.of(tenantUuid)); } private void requireMatchingFence( @@ -1253,6 +1385,31 @@ private Identity resolveIdentity(long accountId, long legacyTenantId) { association); } + private void requirePersistedAccountIdentity(Account account, UUID expectedAccountUuid) { + if (account == null + || account.getId() == null + || account.getId() <= 0L + || !expectedAccountUuid.equals(account.getAccountUuid()) + || account.getAccountUuidProvenance() == null + || !Objects.equals(account.getAccountUuidSourceNumericId(), account.getId())) { + throw new IllegalStateException( + "Fresh snapshot Account UUID does not exactly identify its persisted row"); + } + } + + private void requireCanonicalUuidInput(UUID value, String label) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a non-nil canonical UUID"); + } + } + + private void requireActiveOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Fresh Account membership snapshot requires an active owner transaction"); + } + } + private VerifiedTenantProvenance verifiedProvenance(Identity identity) { ApprovedAssociation association = identity.association(); return new VerifiedTenantProvenance( @@ -1286,11 +1443,15 @@ private void requireActiveMembership(AccountTenantMembership membership) { } private String membershipStreamKey(Identity identity) { + return membershipStreamKey(identity.accountUuid(), identity.tenantUuid()); + } + + private String membershipStreamKey(UUID accountUuid, UUID tenantUuid) { return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "membership/" - + identity.accountUuid() + + accountUuid + "/" - + identity.tenantUuid(); + + tenantUuid; } private String issuerStreamKey() { diff --git a/services/account-service/src/main/resources/db/migration/V39__fresh_uuid_membership_pair_authority.sql b/services/account-service/src/main/resources/db/migration/V39__fresh_uuid_membership_pair_authority.sql new file mode 100644 index 0000000000..e252171d01 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V39__fresh_uuid_membership_pair_authority.sql @@ -0,0 +1,45 @@ +-- The canonical tenant UUID is sufficient identity for fresh Game Design tenants. +-- Only retained associations have a private legacy numeric bridge; never invent one for fresh rows. +-- Fail before changing the table if an earlier candidate write fabricated a fresh numeric key. +-- [jooq ignore start] +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM account_membership_pair_authority + WHERE tenant_provenance_kind = 'FRESH_GAME_DESIGN' + AND legacy_tenant_id IS NOT NULL + ) THEN + RAISE EXCEPTION 'Fresh Account membership pair must not carry a legacy tenant ID' + USING ERRCODE = '23514', + CONSTRAINT = 'account_membership_pair_authority_fresh_legacy_id_migration'; + END IF; +END; +$$; +-- [jooq ignore stop] + +ALTER TABLE account_membership_pair_authority + ALTER COLUMN legacy_tenant_id DROP NOT NULL; + +-- jOOQ's H2 simulator assigns a different generated name to the V36 inline CHECK. +-- Keep the PostgreSQL drop active; skip only this name-specific operation in simulation. +-- [jooq ignore start] +ALTER TABLE account_membership_pair_authority + DROP CONSTRAINT account_membership_pair_authority_legacy_tenant_id_check; +-- [jooq ignore stop] + +ALTER TABLE account_membership_pair_authority + ADD CONSTRAINT account_membership_pair_authority_provenance_legacy_id_check CHECK ( + (tenant_provenance_kind = 'APPROVED_RETAINED' + AND legacy_tenant_id IS NOT NULL + AND legacy_tenant_id > 0) + OR (tenant_provenance_kind = 'FRESH_GAME_DESIGN' + AND legacy_tenant_id IS NULL) + ); + +DROP INDEX account_membership_pair_authority_legacy_scope_uq; + +-- Preserve one-to-one legacy association checks only for retained pairs. +CREATE UNIQUE INDEX account_membership_pair_authority_legacy_scope_uq + ON account_membership_pair_authority (account_uuid, legacy_tenant_id) + WHERE tenant_provenance_kind = 'APPROVED_RETAINED'; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountFreshUuidMembershipSnapshotIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountFreshUuidMembershipSnapshotIntegrationTest.java new file mode 100644 index 0000000000..8ba8dc0c16 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountFreshUuidMembershipSnapshotIntegrationTest.java @@ -0,0 +1,666 @@ +package net.firedevops.firemud.accountservice; + +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.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; + +import java.nio.charset.StandardCharsets; +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.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +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.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.test.GatewayTestProperties; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.DSLContext; +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.test.util.AopTestUtils; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +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=firemud-unit1b" + }) +class AccountFreshUuidMembershipSnapshotIntegrationTest { + @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 AccountMembershipAuthorityEventProducer producer; + @Autowired private AccountAuthorityGenerationRepository authorityGenerationRepository; + @Autowired private AccountAuthorityOutboxRepository authorityOutboxRepository; + @Autowired private FreshTenantIdentityAssociationRepository freshAssociationRepository; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoSpyBean private AccountJoinOperationRepository joinOperationRepository; + @MockitoSpyBean private AccountMembershipPairAuthorityRepository pairAuthorityRepository; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + + @Test + void freshUuidSnapshotEnrollsExactNonAdmittingBaselineAndRetriesWithoutSideEffects() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + FreshTenantCreationEvidence evidence = importFreshTenantAssociation(tenantUuid); + long originalIssuanceFence = issuanceFence(account.accountUuid()); + + var first = readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid); + Map pairRow = membershipPairAuthorityRow(account.accountUuid(), tenantUuid); + + assertThat(first.accountId()).isEqualTo(account.accountUuid().toString()); + assertThat(first.tenantId()).isEqualTo(tenantUuid.toString()); + assertThat(first.membershipExists()).isFalse(); + assertThat(first.membershipLifecycleState()).isEqualTo("MISSING"); + assertThat(first.gameplayAdmissionAllowed()).isFalse(); + assertThat(first.roles()).isEmpty(); + assertThat(first.membershipVersion()).isEqualTo(Map.of(tenantUuid.toString(), "1")); + assertThat(first.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(first.authorityTuple().issuerAuthGeneration()).isEqualTo("1"); + assertThat(first.authorityTuple().accountAuthorityGeneration()).isEqualTo("1"); + assertThat(first.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(tenantUuid.toString(), "1")); + assertThat(first.authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(Map.of(tenantUuid.toString(), "1")); + assertThat(first.authorityTuple().privateRealmGrantVersions()).isEmpty(); + assertThat(first.authorityTuple().accountSecurityCutoff()).isEmpty(); + assertThat(first.authorityTuple().tenantBillingCutoff()).isEmpty(); + assertThat(first.issuanceFence()).isEqualTo(Long.toString(originalIssuanceFence)); + assertThat(first.evaluatedAt()).isNotNull(); + assertThat(first.outboxStreamKey()) + .isEqualTo(membershipStreamKey(account.accountUuid(), tenantUuid)); + assertThat(first.outboxCheckpoints()) + .containsExactlyElementsOf(expectedCheckpoints(account.accountUuid(), tenantUuid)); + assertThat(first.outboxSourceEvidence()).isEmpty(); + assertThat(pairRow) + .containsEntry("account_uuid", account.accountUuid()) + .containsEntry("tenant_uuid", tenantUuid) + .containsEntry("legacy_tenant_id", null) + .containsEntry("tenant_provenance_kind", "FRESH_GAME_DESIGN") + .containsEntry("tenant_source_operation_id", evidence.operationId()) + .containsEntry("tenant_provenance_digest", evidence.evidenceDigest()) + .containsEntry("membership_exists", false) + .containsEntry("membership_version", 1L) + .containsEntry("membership_authority_generation", 1L) + .containsEntry("last_event_sequence", 0L) + .containsEntry("last_event_id", null) + .containsEntry("last_event_digest", null); + assertThat(authorityGeneration("MEMBERSHIP", account.accountUuid(), tenantUuid)).isEqualTo(1L); + assertThat(issuanceFence(account.accountUuid())).isEqualTo(originalIssuanceFence); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countAuthorityStreams(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countFreshCanonicalClaim(tenantUuid)).isEqualTo(1L); + assertThat(countApprovedAssociationForCanonicalTenant(tenantUuid)).isZero(); + + var retry = readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid); + assertThat(retry.accountId()).isEqualTo(first.accountId()); + assertThat(retry.tenantId()).isEqualTo(first.tenantId()); + assertThat(retry.membershipVersion()).isEqualTo(first.membershipVersion()); + assertThat(retry.membershipAuthorityGeneration()) + .isEqualTo(first.membershipAuthorityGeneration()); + assertThat(retry.authorityTuple()).isEqualTo(first.authorityTuple()); + assertThat(retry.issuanceFence()).isEqualTo(first.issuanceFence()); + assertThat(retry.outboxCheckpoints()).isEqualTo(first.outboxCheckpoints()); + assertThat(retry.outboxSourceEvidence()).isEmpty(); + assertThat(membershipPairAuthorityRow(account.accountUuid(), tenantUuid)).isEqualTo(pairRow); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)) + .isEqualTo(1L); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countAuthorityStreams(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(issuanceFence(account.accountUuid())).isEqualTo(originalIssuanceFence); + } + + @Test + void freshUuidSnapshotRejectsUnmappedTenantWithoutEnrollment() { + AccountFixture account = accountFixture(); + UUID unmappedTenantUuid = UUID.randomUUID(); + + assertThatThrownBy( + () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), unmappedTenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("association is absent"); + assertThat(countMembershipPairAuthorities(account.accountUuid(), unmappedTenantUuid)).isZero(); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), unmappedTenantUuid)) + .isZero(); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + } + + @Test + void freshUuidSnapshotRejectsPairProvenanceThatConflictsWithSourceReadback() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + FreshTenantCreationEvidence evidence = importFreshTenantAssociation(tenantUuid); + dsl.execute( + "INSERT INTO account_membership_pair_authority " + + "(account_uuid, tenant_uuid, legacy_tenant_id, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest, membership_exists, " + + "membership_version, membership_authority_generation, last_event_sequence, " + + "last_event_id, last_event_digest, last_transition_invalidated) " + + "VALUES (?, ?, NULL, 'FRESH_GAME_DESIGN', ?, ?, FALSE, 1, 1, 0, NULL, NULL, FALSE)", + account.accountUuid(), + tenantUuid, + UUID.randomUUID(), + evidence.evidenceDigest()); + Map conflictingPair = + membershipPairAuthorityRow(account.accountUuid(), tenantUuid); + + assertThatThrownBy( + () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with verified association provenance"); + assertThat(membershipPairAuthorityRow(account.accountUuid(), tenantUuid)) + .isEqualTo(conflictingPair); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + } + + @Test + void freshUuidSnapshotRollsBackGenerationAndPairWhenEnrollmentCompositionFails() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + importFreshTenantAssociation(tenantUuid); + AccountMembershipPairAuthorityRepository pairAuthorityTarget = + AopTestUtils.getUltimateTargetObject(pairAuthorityRepository); + doAnswer( + invocation -> { + invocation.callRealMethod(); + throw new IllegalStateException("simulated failure after pair enrollment"); + }) + .when(pairAuthorityTarget) + .enrollAbsence(eq(account.accountUuid()), eq(tenantUuid), any()); + + assertThatThrownBy( + () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulated failure after pair enrollment"); + assertThat(countMembershipPairAuthorities(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countAuthorityStreams(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + } + + @Test + void freshUuidSnapshotRejectsCommittedMembershipHistoryBeforeBaselineEnrollment() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + importFreshTenantAssociation(tenantUuid); + String streamKey = membershipStreamKey(account.accountUuid(), tenantUuid); + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> + authorityOutboxRepository.append( + streamKey, + "fresh-history-" + UUID.randomUUID(), + UUID.randomUUID().toString(), + "sha256:" + "a".repeat(64), + "{}".getBytes(StandardCharsets.UTF_8))); + + assertThatThrownBy( + () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("retained authority-event history"); + assertThat(countMembershipPairAuthorities(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(streamKey)).isEqualTo(1L); + assertThat(countAuthorityStreams(streamKey)).isEqualTo(1L); + } + + @Test + void freshUuidSnapshotRejectsAdvancedPairAndGenerationWithoutResettingEither() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + importFreshTenantAssociation(tenantUuid); + var original = readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid); + Map pairRow = membershipPairAuthorityRow(account.accountUuid(), tenantUuid); + dsl.execute( + "UPDATE account_authority_generations SET generation = 2, source_version = 2 " + + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? AND tenant_uuid = ?", + account.accountUuid(), + tenantUuid); + + assertThatThrownBy( + () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "membership authority generation cannot prove its sequence-zero baseline"); + assertThat(membershipPairAuthorityRow(account.accountUuid(), tenantUuid)).isEqualTo(pairRow); + assertThat(authorityGeneration("MEMBERSHIP", account.accountUuid(), tenantUuid)).isEqualTo(2L); + assertThat(countAuthorityEvents(original.outboxStreamKey())).isZero(); + + dsl.execute( + "UPDATE account_membership_pair_authority SET membership_exists = TRUE, " + + "membership_version = 2, membership_authority_generation = 2, " + + "last_event_sequence = 1, last_event_id = ?, last_event_digest = ?, " + + "last_transition_invalidated = TRUE WHERE account_uuid = ? AND tenant_uuid = ?", + UUID.randomUUID().toString(), + "sha256:" + "b".repeat(64), + account.accountUuid(), + tenantUuid); + Map progressedPair = + membershipPairAuthorityRow(account.accountUuid(), tenantUuid); + + assertThatThrownBy( + () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid)) + .isInstanceOf(IllegalStateException.class); + assertThat(membershipPairAuthorityRow(account.accountUuid(), tenantUuid)) + .isEqualTo(progressedPair); + assertThat(countAuthorityEvents(original.outboxStreamKey())).isZero(); + } + + @Test + void freshUuidSnapshotRejectsAdvancedTenantGenerationAndRollsBackBaselineWrites() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + importFreshTenantAssociation(tenantUuid); + dsl.execute( + "UPDATE account_authority_generations SET generation = 2, source_version = 2 " + + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + tenantUuid); + + assertThatThrownBy( + () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "tenant authority generation cannot prove its sequence-zero baseline"); + assertThat(authorityGeneration("TENANT", null, tenantUuid)).isEqualTo(2L); + assertThat(countMembershipPairAuthorities(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countAuthorityStreams(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + } + + @Test + void concurrentFreshUuidSnapshotCallsInitializeOneExactPairBaseline() throws Exception { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + importFreshTenantAssociation(tenantUuid); + ExecutorService executor = Executors.newFixedThreadPool(2); + CountDownLatch firstSnapshotReady = new CountDownLatch(1); + CountDownLatch releaseFirstSnapshot = new CountDownLatch(1); + CountDownLatch secondLockAttempted = new CountDownLatch(1); + AtomicReference firstBackendPid = new AtomicReference<>(); + AtomicReference secondBackendPid = new AtomicReference<>(); + AtomicInteger lockInvocations = new AtomicInteger(); + doAnswer( + invocation -> { + if (lockInvocations.incrementAndGet() == 2) { + secondBackendPid.set(currentBackendPid()); + secondLockAttempted.countDown(); + } + return invocation.callRealMethod(); + }) + .when(joinOperationRepository) + .lockAccount(anyLong()); + try { + Future first = + executor.submit( + () -> + new TransactionTemplate(transactionManager) + .execute( + status -> { + var snapshot = + producer.readFreshNeverJoinedMembershipSnapshot( + account.accountUuid(), tenantUuid); + firstBackendPid.set(currentBackendPid()); + firstSnapshotReady.countDown(); + await(releaseFirstSnapshot); + return snapshot; + })); + assertThat(firstSnapshotReady.await(10, TimeUnit.SECONDS)).isTrue(); + + Future second = + executor.submit( + () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid)); + assertThat(secondLockAttempted.await(10, TimeUnit.SECONDS)).isTrue(); + awaitAccountFenceLockWait(firstBackendPid.get(), secondBackendPid.get()); + assertThat(second.isDone()).isFalse(); + + releaseFirstSnapshot.countDown(); + var firstSnapshot = first.get(20, TimeUnit.SECONDS); + var secondSnapshot = second.get(20, TimeUnit.SECONDS); + assertThat(firstSnapshot.membershipVersion()).isEqualTo(Map.of(tenantUuid.toString(), "1")); + assertThat(secondSnapshot.membershipVersion()).isEqualTo(firstSnapshot.membershipVersion()); + assertThat(secondSnapshot.authorityTuple()).isEqualTo(firstSnapshot.authorityTuple()); + assertThat(secondSnapshot.outboxCheckpoints()).isEqualTo(firstSnapshot.outboxCheckpoints()); + assertThat(countMembershipPairAuthorities(account.accountUuid(), tenantUuid)).isEqualTo(1L); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)) + .isEqualTo(1L); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + } catch (ExecutionException exception) { + throw new AssertionError("Concurrent fresh snapshot read failed", exception.getCause()); + } finally { + releaseFirstSnapshot.countDown(); + executor.shutdownNow(); + } + } + + private AccountFixture accountFixture() { + String suffix = UUID.randomUUID().toString().replace("-", ""); + long accountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) " + + "VALUES (?, ?, ?) RETURNING id", + "fresh-snapshot-" + suffix, + "fresh-snapshot-" + suffix + "@example.com", + "test-hash") + .fetchOne(0, Long.class)); + UUID accountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) + .fetchOne(0, UUID.class)); + dsl.execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, account_uuid, generation, source_version) " + + "VALUES ('ACCOUNT', ?, 1, 1)", + accountUuid); + dsl.execute( + "INSERT INTO account_authority_issuance_fences " + + "(account_uuid, issuance_fence, source_version) VALUES (?, 1, 1)", + accountUuid); + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> + authorityGenerationRepository.initializeIssuerIfAbsent( + AccountServiceImpl.ACCOUNT_JWT_ISSUER)); + return new AccountFixture(accountId, accountUuid); + } + + private FreshTenantCreationEvidence importFreshTenantAssociation(UUID canonicalTenantUuid) { + UUID creationRequestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String targetNamespace = "firemud-unit1b"; + String sourceGameTenantKey = + "fresh-" + UUID.randomUUID().toString().replace("-", "").substring(0, 20); + String requestDigest = + GameTenantCreationDigest.requestDigest( + targetNamespace, creationRequestId, sourceGameTenantKey, "Fresh tenant", null); + long sourceGameRowId = positiveRandomLong(); + String provenanceKind = "NEW_GAME_ROW"; + FreshTenantCreationEvidence evidence = + new FreshTenantCreationEvidence( + 1, + targetNamespace, + creationRequestId, + operationId, + requestDigest, + canonicalTenantUuid, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + GameTenantCreationDigest.evidenceDigest( + targetNamespace, + creationRequestId, + operationId, + requestDigest, + canonicalTenantUuid, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> { + freshAssociationRepository.importVerified(evidence); + authorityGenerationRepository.initializeTenantIfAbsent(canonicalTenantUuid); + }); + return evidence; + } + + private AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot + readFreshNeverJoinedMembershipSnapshot(UUID accountUuid, UUID tenantUuid) { + return new TransactionTemplate(transactionManager) + .execute( + status -> producer.readFreshNeverJoinedMembershipSnapshot(accountUuid, tenantUuid)); + } + + private Map membershipPairAuthorityRow(UUID accountUuid, UUID tenantUuid) { + var row = + dsl.resultQuery( + "SELECT * FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + tenantUuid) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + + private long countMembershipPairAuthorities(UUID accountUuid, UUID tenantUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + tenantUuid) + .fetchOne(0, Long.class)); + } + + private long countMembershipAuthorityGenerations(UUID accountUuid, UUID tenantUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_generations " + + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? " + + "AND tenant_uuid = ?", + accountUuid, + tenantUuid) + .fetchOne(0, Long.class)); + } + + private long authorityGeneration(String scopeKind, UUID accountUuid, UUID tenantUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = ? AND account_uuid IS NOT DISTINCT FROM ? " + + "AND tenant_uuid IS NOT DISTINCT FROM ?", + scopeKind, + accountUuid, + tenantUuid) + .fetchOne(0, Long.class)); + } + + private long issuanceFence(UUID accountUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT issuance_fence FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + accountUuid) + .fetchOne(0, Long.class)); + } + + private long countMembershipsForAccount(long accountId) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ?", accountId) + .fetchOne(0, Long.class)); + } + + private long countMembershipTransitionReceiptsForAccount(long accountId) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_membership_transition_receipts WHERE account_id = ?", + accountId) + .fetchOne(0, Long.class)); + } + + private long countAuthorityEvents(String streamKey) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class)); + } + + private long countAuthorityStreams(String streamKey) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class)); + } + + private long countFreshCanonicalClaim(UUID tenantUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_canonical_tenant_identity_claims " + + "WHERE canonical_tenant_id = ? AND identity_kind = 'FRESH_GAME_DESIGN'", + tenantUuid) + .fetchOne(0, Long.class)); + } + + private long countApprovedAssociationForCanonicalTenant(UUID tenantUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_approved_legacy_tenant_associations " + + "WHERE canonical_tenant_id = ?", + tenantUuid) + .fetchOne(0, Long.class)); + } + + private String membershipStreamKey(UUID accountUuid, UUID tenantUuid) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountUuid + + "/" + + tenantUuid; + } + + private List expectedCheckpoints(UUID accountUuid, UUID tenantUuid) { + return List.of( + new OutboxCheckpointEntry( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + accountUuid, "0"), + new OutboxCheckpointEntry( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "issuer/" + + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + "0"), + new OutboxCheckpointEntry(membershipStreamKey(accountUuid, tenantUuid), "0"), + new OutboxCheckpointEntry( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "tenant/" + tenantUuid, "0")); + } + + private long positiveRandomLong() { + long candidate = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + return candidate == 0L ? 1L : candidate; + } + + private Integer currentBackendPid() { + return dsl.resultQuery("SELECT pg_backend_pid()").fetchOne(0, Integer.class); + } + + private void awaitAccountFenceLockWait(Integer snapshotBackendPid, Integer waitingBackendPid) + throws InterruptedException { + assertThat(snapshotBackendPid).isNotNull(); + assertThat(waitingBackendPid).isNotNull(); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + Boolean blockedBySnapshot = + dsl.resultQuery( + "SELECT CAST(? AS integer) = ANY(pg_blocking_pids(CAST(? AS integer)))", + snapshotBackendPid, + waitingBackendPid) + .fetchOne(0, Boolean.class); + if (Boolean.TRUE.equals(blockedBySnapshot)) { + return; + } + Thread.sleep(10); + } + throw new AssertionError( + "second fresh snapshot transaction did not block on the Account-row fence"); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(60, TimeUnit.SECONDS)) { + throw new IllegalStateException("fresh snapshot concurrency test timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("fresh snapshot concurrency test was interrupted", exception); + } + } + + private record AccountFixture(long accountId, UUID accountUuid) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryIntegrationTest.java index 5e1f247fed..eb2d0a61f1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryIntegrationTest.java @@ -4,7 +4,9 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Map; +import java.util.Objects; import java.util.UUID; +import javax.sql.DataSource; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairTransition; @@ -12,6 +14,7 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.FlywayException; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; @@ -27,14 +30,14 @@ @Testcontainers(disabledWithoutDocker = true) class AccountMembershipPairAuthorityRepositoryIntegrationTest { - private static final String SCHEMA = "account_membership_pair_authority_proof"; + private static final String SCHEMA_PREFIX = "pair_authority_proof_"; @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @Test void immutableValueTypesRejectContradictoryAuthorityEvidence() { - VerifiedTenantProvenance provenance = provenance(701L, TenantProvenanceKind.FRESH_GAME_DESIGN); + VerifiedTenantProvenance provenance = provenance(null, TenantProvenanceKind.FRESH_GAME_DESIGN); UUID accountUuid = UUID.randomUUID(); UUID tenantUuid = UUID.randomUUID(); @@ -61,23 +64,283 @@ void immutableValueTypesRejectContradictoryAuthorityEvidence() { assertThatThrownBy( () -> new VerifiedTenantProvenance( - 701L, + null, TenantProvenanceKind.FRESH_GAME_DESIGN, UUID.randomUUID(), "SHA256:" + "a".repeat(64))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical lowercase SHA-256"); + assertThatThrownBy( + () -> + new VerifiedTenantProvenance( + 701L, TenantProvenanceKind.FRESH_GAME_DESIGN, UUID.randomUUID(), digest(1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must not carry a legacy"); + assertThatThrownBy( + () -> + new VerifiedTenantProvenance( + null, TenantProvenanceKind.APPROVED_RETAINED, UUID.randomUUID(), digest(1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive legacy tenant ID"); assertThatThrownBy(() -> new ProvenPositiveCheckpoint(1L, 1L, 0L, "event", digest(1), false)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("incomplete"); } @Test - void enrollmentAndTransitionsPreserveExactPositiveAuthorityAndProvenance() { + void freshPairsUseUuidIdentityWithoutLegacyAliasesAndRequireTheOwnerTransaction() { + TestContext context = newTestContext(); + UUID accountUuid = insertAccount(context.setupDsl()); + UUID firstTenantUuid = UUID.randomUUID(); + UUID secondTenantUuid = UUID.randomUUID(); + VerifiedTenantProvenance firstFresh = provenance(null, TenantProvenanceKind.FRESH_GAME_DESIGN); + VerifiedTenantProvenance secondFresh = provenance(null, TenantProvenanceKind.FRESH_GAME_DESIGN); + + assertThatThrownBy(() -> context.repository().readForUpdate(accountUuid, firstTenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + + PairAuthority first = + inTransaction( + context.transaction(), + () -> context.repository().enrollAbsence(accountUuid, firstTenantUuid, firstFresh)); + PairAuthority second = + inTransaction( + context.transaction(), + () -> context.repository().enrollAbsence(accountUuid, secondTenantUuid, secondFresh)); + assertThat(first.provenance().legacyTenantId()).isNull(); + assertThat(second.provenance().legacyTenantId()).isNull(); + assertThat( + Objects.requireNonNull( + context + .setupDsl() + .fetchOne( + "SELECT count(*) FROM account_membership_pair_authority " + + "WHERE account_uuid = ? " + + "AND tenant_provenance_kind = 'FRESH_GAME_DESIGN' " + + "AND legacy_tenant_id IS NULL", + accountUuid), + "Fresh pair count query must return a row") + .get(0, Long.class)) + .isEqualTo(2L); + + VerifiedTenantProvenance retained = provenance(705L, TenantProvenanceKind.APPROVED_RETAINED); + UUID retainedTenantUuid = UUID.randomUUID(); + inTransaction( + context.transaction(), + () -> context.repository().enrollAbsence(accountUuid, retainedTenantUuid, retained)); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .enrollAbsence( + accountUuid, + UUID.randomUUID(), + provenance(705L, TenantProvenanceKind.APPROVED_RETAINED)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with an existing pair authority"); + + UUID rolledBackTenantUuid = UUID.randomUUID(); + assertThatThrownBy( + () -> + context + .transaction() + .execute( + status -> { + context + .repository() + .enrollAbsence(accountUuid, rolledBackTenantUuid, firstFresh); + throw new IllegalStateException("rollback pair enrollment"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("rollback pair enrollment"); + assertThat( + Objects.requireNonNull( + context + .setupDsl() + .fetchOne( + "SELECT count(*) FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + rolledBackTenantUuid), + "Rolled-back pair count query must return a row") + .get(0, Long.class)) + .isZero(); + } + + @Test + void databaseRejectsRetainedNullAndFreshNumericLegacyKeys() { TestContext context = newTestContext(); UUID accountUuid = insertAccount(context.setupDsl()); + + assertThatThrownBy( + () -> + insertPair( + context.setupDsl(), + accountUuid, + UUID.randomUUID(), + null, + TenantProvenanceKind.APPROVED_RETAINED)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + insertPair( + context.setupDsl(), + accountUuid, + UUID.randomUUID(), + 706L, + TenantProvenanceKind.FRESH_GAME_DESIGN)) + .isInstanceOf(DataAccessException.class); + } + + @Test + void v39PreservesRetainedPairHistoryAndEnforcesUuidOnlyFreshRows() { + TestContext context = newTestContext(newSchema(), "38"); + UUID accountUuid = insertAccount(context.setupDsl()); + UUID retainedTenantUuid = UUID.randomUUID(); + VerifiedTenantProvenance retained = provenance(707L, TenantProvenanceKind.APPROVED_RETAINED); + insertPair( + context.setupDsl(), + accountUuid, + retainedTenantUuid, + retained.legacyTenantId(), + retained.kind(), + retained.sourceOperationId(), + retained.digest()); + org.jooq.Record retainedBefore = + context + .setupDsl() + .fetchOne( + "SELECT * FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + retainedTenantUuid); + + UUID advancedTenantUuid = UUID.randomUUID(); + VerifiedTenantProvenance advancedRetained = + provenance(709L, TenantProvenanceKind.APPROVED_RETAINED); + ProvenPositiveCheckpoint advancedCheckpoint = + new ProvenPositiveCheckpoint(8L, 3L, 11L, "retained-event-11", digest(9), true); + PairAuthority advancedAuthority = + inTransaction( + context.transaction(), + () -> + context + .repository() + .enrollProvenPositive( + accountUuid, advancedTenantUuid, advancedRetained, advancedCheckpoint)); + org.jooq.Record advancedBefore = + context + .setupDsl() + .fetchOne( + "SELECT * FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + advancedTenantUuid); + + flyway(context.dataSource(), context.schema(), null).migrate(); + org.jooq.Record retainedAfter = + context + .setupDsl() + .fetchOne( + "SELECT * FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + retainedTenantUuid); + org.jooq.Record advancedAfter = + context + .setupDsl() + .fetchOne( + "SELECT * FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + advancedTenantUuid); + assertThat(retainedAfter).isEqualTo(retainedBefore); + assertThat(advancedAfter).isEqualTo(advancedBefore); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readForUpdate(accountUuid, retainedTenantUuid))) + .contains( + new PairAuthority( + accountUuid, retainedTenantUuid, retained, false, 1L, 1L, 0L, null, null, false)); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readForUpdate(accountUuid, advancedTenantUuid))) + .contains(advancedAuthority); + + PairAuthority firstFresh = + inTransaction( + context.transaction(), + () -> + context + .repository() + .enrollAbsence( + accountUuid, + UUID.randomUUID(), + provenance(null, TenantProvenanceKind.FRESH_GAME_DESIGN))); + PairAuthority secondFresh = + inTransaction( + context.transaction(), + () -> + context + .repository() + .enrollAbsence( + accountUuid, + UUID.randomUUID(), + provenance(null, TenantProvenanceKind.FRESH_GAME_DESIGN))); + assertThat(firstFresh.tenantUuid()).isNotEqualTo(secondFresh.tenantUuid()); + assertThat(firstFresh.provenance().legacyTenantId()).isNull(); + assertThat(secondFresh.provenance().legacyTenantId()).isNull(); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .enrollAbsence( + accountUuid, + UUID.randomUUID(), + provenance(707L, TenantProvenanceKind.APPROVED_RETAINED)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with an existing pair authority"); + } + + @Test + void v39RefusesToRewriteAnExistingFreshNumericPair() { + TestContext context = newTestContext(newSchema(), "38"); + UUID accountUuid = insertAccount(context.setupDsl()); UUID tenantUuid = UUID.randomUUID(); - VerifiedTenantProvenance fresh = provenance(702L, TenantProvenanceKind.FRESH_GAME_DESIGN); + insertPair( + context.setupDsl(), accountUuid, tenantUuid, 708L, TenantProvenanceKind.FRESH_GAME_DESIGN); + + assertThatThrownBy(() -> flyway(context.dataSource(), context.schema(), null).migrate()) + .isInstanceOf(FlywayException.class); + assertThat( + Objects.requireNonNull( + context + .setupDsl() + .fetchOne( + "SELECT legacy_tenant_id FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + tenantUuid), + "Rejected migration must leave the existing pair row") + .get(0, Long.class)) + .isEqualTo(708L); + } + + @Test + void enrollmentAndTransitionsPreserveExactAuthorityAndProvenance() { + TestContext context = newTestContext(); + UUID accountUuid = insertAccount(context.setupDsl()); + UUID tenantUuid = UUID.randomUUID(); + VerifiedTenantProvenance fresh = provenance(null, TenantProvenanceKind.FRESH_GAME_DESIGN); PairAuthority baseline = inTransaction( @@ -192,7 +455,7 @@ void enrollmentAndTransitionsPreserveExactPositiveAuthorityAndProvenance() { VerifiedTenantProvenance wrongProvenance = new VerifiedTenantProvenance( - 702L, TenantProvenanceKind.FRESH_GAME_DESIGN, UUID.randomUUID(), digest(4)); + null, TenantProvenanceKind.FRESH_GAME_DESIGN, UUID.randomUUID(), digest(4)); assertThatThrownBy( () -> inTransaction( @@ -203,20 +466,6 @@ void enrollmentAndTransitionsPreserveExactPositiveAuthorityAndProvenance() { .enrollAbsence(accountUuid, tenantUuid, wrongProvenance))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("conflicts with verified association provenance"); - assertThatThrownBy( - () -> - inTransaction( - context.transaction(), - () -> - context - .repository() - .enrollAbsence( - accountUuid, - UUID.randomUUID(), - provenance(702L, TenantProvenanceKind.FRESH_GAME_DESIGN)))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("conflicts with an existing pair authority"); - assertThatThrownBy( () -> inTransaction( @@ -335,7 +584,7 @@ void positiveRetainedEnrollmentUsesSuppliedCountersAndRejectsSeqZeroOrChangedEvi .enrollProvenPositive( accountUuid, tenantUuid, - provenance(703L, TenantProvenanceKind.FRESH_GAME_DESIGN), + provenance(null, TenantProvenanceKind.FRESH_GAME_DESIGN), checkpoint))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("approved retained tenant provenance"); @@ -375,29 +624,47 @@ void databaseRejectsPositiveSequenceWithoutEventDigest() { } private TestContext newTestContext() { + return newTestContext(newSchema(), null); + } + + private TestContext newTestContext(String schema, String targetVersion) { DriverManagerDataSource dataSource = new DriverManagerDataSource(); - String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; - dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + SCHEMA); + dataSource.setUrl(postgres.getJdbcUrl()); 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(); + dataSource.setSchema(schema); + flyway(dataSource, schema, targetVersion).migrate(); DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + assertThat(setupDsl.fetchOne("SELECT current_schema()").get(0, String.class)).isEqualTo(schema); DSLContext transactionDsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); return new TestContext( + schema, + dataSource, setupDsl, new AccountMembershipPairAuthorityRepository(transactionDsl), new TransactionTemplate(new DataSourceTransactionManager(dataSource))); } + private String newSchema() { + return SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); + } + + private Flyway flyway(DataSource dataSource, String schema, String targetVersion) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (targetVersion != null) { + configuration.target(targetVersion); + } + return configuration.load(); + } + private UUID insertAccount(DSLContext dsl) { String unique = UUID.randomUUID().toString().replace("-", ""); return dsl.resultQuery( @@ -409,10 +676,42 @@ private UUID insertAccount(DSLContext dsl) { .fetchOne(0, UUID.class); } - private VerifiedTenantProvenance provenance(long legacyTenantId, TenantProvenanceKind kind) { + private VerifiedTenantProvenance provenance(Long legacyTenantId, TenantProvenanceKind kind) { return new VerifiedTenantProvenance(legacyTenantId, kind, UUID.randomUUID(), digest(1)); } + private void insertPair( + DSLContext dsl, + UUID accountUuid, + UUID tenantUuid, + Long legacyTenantId, + TenantProvenanceKind kind) { + insertPair(dsl, accountUuid, tenantUuid, legacyTenantId, kind, UUID.randomUUID(), digest(1)); + } + + private void insertPair( + DSLContext dsl, + UUID accountUuid, + UUID tenantUuid, + Long legacyTenantId, + TenantProvenanceKind kind, + UUID sourceOperationId, + String evidenceDigest) { + dsl.execute( + "INSERT INTO account_membership_pair_authority " + + "(account_uuid, tenant_uuid, legacy_tenant_id, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest, membership_exists, " + + "membership_version, membership_authority_generation, last_event_sequence, " + + "last_event_id, last_event_digest, last_transition_invalidated) " + + "VALUES (?, ?, ?, ?, ?, ?, FALSE, 1, 1, 0, NULL, NULL, FALSE)", + accountUuid, + tenantUuid, + legacyTenantId, + kind.name(), + sourceOperationId, + evidenceDigest); + } + private String digest(int digit) { return "sha256:" + Integer.toString(digit).repeat(64); } @@ -423,6 +722,8 @@ private T inTransaction( } private record TestContext( + String schema, + DataSource dataSource, DSLContext setupDsl, AccountMembershipPairAuthorityRepository repository, TransactionTemplate transaction) {} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java new file mode 100644 index 0000000000..5540800e32 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java @@ -0,0 +1,198 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairTransition; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.ProvenPositiveCheckpoint; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class AccountMembershipPairAuthorityRepositoryTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_UUID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID OPERATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String EVENT_DIGEST = "sha256:" + "a".repeat(64); + private static final String SOURCE_DIGEST = "sha256:" + "b".repeat(64); + + @Test + void verifiedProvenanceRequiresKindQualifiedLegacyIdentity() { + VerifiedTenantProvenance fresh = freshProvenance(); + VerifiedTenantProvenance retained = retainedProvenance(72L); + + assertThat(fresh.legacyTenantId()).isNull(); + assertThat(fresh.kind()).isEqualTo(TenantProvenanceKind.FRESH_GAME_DESIGN); + assertThat(retained.legacyTenantId()).isEqualTo(72L); + assertThat(retained.kind()).isEqualTo(TenantProvenanceKind.APPROVED_RETAINED); + + assertThatThrownBy( + () -> + new VerifiedTenantProvenance( + 72L, TenantProvenanceKind.FRESH_GAME_DESIGN, OPERATION_ID, SOURCE_DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must not carry a legacy tenant ID"); + assertThatThrownBy( + () -> + new VerifiedTenantProvenance( + null, TenantProvenanceKind.APPROVED_RETAINED, OPERATION_ID, SOURCE_DIGEST)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive legacy tenant ID"); + assertThatThrownBy(() -> retainedProvenance(0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive legacy tenant ID"); + assertThatThrownBy(() -> retainedProvenance(-1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive legacy tenant ID"); + } + + @Test + void pairRecordsPreservePositiveBaselineAndEventShapes() { + PairAuthority baseline = + new PairAuthority( + ACCOUNT_UUID, TENANT_UUID, freshProvenance(), false, 1L, 1L, 0L, null, null, false); + assertThat(baseline.membershipVersion()).isEqualTo(1L); + assertThat(baseline.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(baseline.lastEventSequence()).isZero(); + assertThat(baseline.membershipExists()).isFalse(); + + PairAuthority joined = + new PairAuthority( + ACCOUNT_UUID, + TENANT_UUID, + freshProvenance(), + true, + 2L, + 1L, + 1L, + "join-event-1", + EVENT_DIGEST, + false); + assertThat(joined.membershipVersion()).isEqualTo(2L); + assertThat(joined.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(joined.lastEventSequence()).isEqualTo(1L); + + PairTransition leave = new PairTransition(false, 2L, "leave-event-2", EVENT_DIGEST, true); + assertThat(leave.eventSequence()).isEqualTo(2L); + assertThat(leave.callerBoundAuthorityInvalidated()).isTrue(); + ProvenPositiveCheckpoint retainedCheckpoint = + new ProvenPositiveCheckpoint(8L, 3L, 11L, "retained-event-11", EVENT_DIGEST, true); + assertThat(retainedCheckpoint.membershipVersion()).isEqualTo(8L); + assertThat(retainedCheckpoint.membershipAuthorityGeneration()).isEqualTo(3L); + assertThat(retainedCheckpoint.eventSequence()).isEqualTo(11L); + + assertThatThrownBy( + () -> + new PairAuthority( + ACCOUNT_UUID, + TENANT_UUID, + freshProvenance(), + false, + 0L, + 1L, + 0L, + null, + null, + false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("incomplete"); + assertThatThrownBy( + () -> + new PairAuthority( + ACCOUNT_UUID, + TENANT_UUID, + freshProvenance(), + false, + 1L, + 0L, + 0L, + null, + null, + false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("incomplete"); + assertThatThrownBy( + () -> + new PairAuthority( + ACCOUNT_UUID, + TENANT_UUID, + freshProvenance(), + true, + 1L, + 1L, + 0L, + null, + null, + false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Sequence-zero"); + assertThatThrownBy( + () -> + new PairAuthority( + ACCOUNT_UUID, + TENANT_UUID, + freshProvenance(), + true, + 2L, + 1L, + 1L, + " ", + EVENT_DIGEST, + false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("event evidence"); + assertThatThrownBy( + () -> new ProvenPositiveCheckpoint(8L, 3L, 0L, "event-0", EVENT_DIGEST, false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("incomplete"); + assertThatThrownBy(() -> new PairTransition(true, 0L, "event-0", EVENT_DIGEST, false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("incomplete"); + } + + @Test + void directRepositoryOperationsRequireOwnerTransactionBeforeDslAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountMembershipPairAuthorityRepository repository = + new AccountMembershipPairAuthorityRepository(dsl); + PairAuthority baseline = + new PairAuthority( + ACCOUNT_UUID, TENANT_UUID, freshProvenance(), false, 1L, 1L, 0L, null, null, false); + PairTransition transition = new PairTransition(true, 1L, "join-event-1", EVENT_DIGEST, false); + ProvenPositiveCheckpoint checkpoint = + new ProvenPositiveCheckpoint(8L, 3L, 11L, "retained-event-11", EVENT_DIGEST, true); + + assertThatThrownBy(() -> repository.enrollAbsence(ACCOUNT_UUID, TENANT_UUID, freshProvenance())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + assertThatThrownBy( + () -> + repository.enrollProvenPositive( + ACCOUNT_UUID, TENANT_UUID, retainedProvenance(72L), checkpoint)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + assertThatThrownBy(() -> repository.readForUpdate(ACCOUNT_UUID, TENANT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + assertThatThrownBy(() -> repository.commitTransition(baseline, transition)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + + verifyNoInteractions(dsl); + } + + private VerifiedTenantProvenance freshProvenance() { + return new VerifiedTenantProvenance( + null, TenantProvenanceKind.FRESH_GAME_DESIGN, OPERATION_ID, SOURCE_DIGEST); + } + + private VerifiedTenantProvenance retainedProvenance(long legacyTenantId) { + return new VerifiedTenantProvenance( + legacyTenantId, TenantProvenanceKind.APPROVED_RETAINED, OPERATION_ID, SOURCE_DIGEST); + } +} 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 new file mode 100644 index 0000000000..4efaec3bf0 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java @@ -0,0 +1,49 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +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.FreshTenantIdentityAssociationRepository; +import org.junit.jupiter.api.Test; + +class AccountMembershipAuthorityEventProducerTest { + @Test + void freshSnapshotRequiresOwnerTransactionBeforeRepositoryReads() { + AccountJoinOperationRepository joinOperationRepository = + mock(AccountJoinOperationRepository.class); + AccountRepository accountRepository = mock(AccountRepository.class); + FreshTenantIdentityAssociationRepository freshAssociationRepository = + mock(FreshTenantIdentityAssociationRepository.class); + AccountMembershipAuthorityEventProducer producer = + new AccountMembershipAuthorityEventProducer( + joinOperationRepository, + mock(AccountMembershipPairAuthorityRepository.class), + accountRepository, + mock(AccountTenantIdentityResolver.class), + freshAssociationRepository, + mock(AccountAuthorityGenerationRepository.class), + mock(AccountAuthorityOutboxRepository.class), + mock(AccountMembershipTransitionReceiptRepository.class), + mock(AccountTenantMembershipRepository.class), + mock(AccountTenantMembershipRoleSnapshotRepository.class)); + + assertThatThrownBy( + () -> + producer.readFreshNeverJoinedMembershipSnapshot( + UUID.randomUUID(), UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + verifyNoInteractions(joinOperationRepository, accountRepository, freshAssociationRepository); + } +}