From 84e90bf2464583df7e11e11d60e7c571de13de81 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 24 Nov 2026 02:41:45 +1300 Subject: [PATCH 01/14] Reapply exact paid NEW child atop the inherited postclaim Redis fixture --- .../account-service/api-contracts.md | 2 + .../account-service/runtime-and-data.md | 2 +- .../player-access-and-session.md | 2 + ...ccountGameplayAdmissionCurrentSources.java | 225 +++++-- .../AccountGameplayAdmissionLeaseOwner.java | 81 +-- ...meplayAdmissionOriginalCommitExecutor.java | 20 +- .../AccountGameplayAdmissionPaidSource.java | 161 +++++ ...iginalNewBoundGameplayCredentialOwner.java | 193 ++++-- .../repository/AccountRepository.java | 7 + .../service/impl/AccountServiceImpl.java | 4 + ...CurrentSourcesPostgresIntegrationTest.java | 576 +++++++++++++++++- ...ameplayCredentialOwnerIntegrationTest.java | 340 ++++++++--- ...nonicalHostingSubscriptionTestFixture.java | 10 + ...nicalFirstJoinPostgresIntegrationTest.java | 44 ++ ...ccountGameplayAdmissionLeaseOwnerTest.java | 16 + .../service/impl/AccountServiceImplTest.java | 19 + 16 files changed, 1470 insertions(+), 232 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionPaidSource.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index a43966db13..6277453d81 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -306,6 +306,8 @@ The shared codec preserves the existing 64 KiB lease and 15-second lifetime boun The never-admitted abort uses separate negative-purpose messages and the reverse `GetOriginalNewNeverAdmittedDecision` Game Session RPC. Account independently reads Game Session’s qualified exact-original closure before retaining a negative resolution; no provisional or committed decision is synthesized. The [interrupted original NEW contract](../../system-architecture-session-behavior.md#canonical-public-production-new-admission) owns irreversible selection, continuous qualification and cleanup requirements. The ordinary positive decision readers reject this purpose. The reverse negative read returns bounded `FAILED_PRECONDITION` for definitive retained-source or selector conflicts, `UNAVAILABLE` for missing or withdrawn closure qualification and transient SQL/Redis outages, and `INTERNAL` for unexpected or response-encoding failures. Caller and malformed-request refusals remain `PERMISSION_DENIED` and `INVALID_ARGUMENT`. These manual receivers remain unregistered. +The local lease owner accepts explicit `AccountGameplayAdmissionPaidSource` composition for paid NEW sources; its existing DEMO-only constructor refuses paid tenants. This adds no wire field, caller source selector or registered method. Source and proof limits are recorded in [canonical NEW admission components](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). + #### Unknown-decision abort resolution An `ABORTED` original operation whose decision was unknown retains its null decision, original lease bytes and cleanup reference permanently. A later transition-selected Abort may return separate Account-owned resolution evidence; it never changes that original terminal result. Account verifies the exact existing provisional Game Session decision through its protected reverse read outside SQL, then rechecks the current authenticated caller and unchanged original abort under a fresh writable serializable transaction before recording one immutable resolution. The resolution binds its own identity, the original lease UUID, fence and canonical digest, the original cleanup UUID and the verified transition UUID. It grants neither admission nor completed Game Session cleanup. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index d24eb4fa4b..8410016035 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -22,7 +22,7 @@ Ordinary control-UI, gameplay password/email-OTP, and player-bootstrap issuance The global Account REST selectors resolve public UUIDs to private numeric rows before Account-local service calls. Private numeric row keys remain local to storage; the [Account API contract](./api-contracts.md#rest-apis) owns caller authorization, selector, and failure behavior. The final receiving composition carries UUID identity through shared context, gRPC and Logging consumers. Tenant representations follow the [Account tenant identifier boundary](./api-contracts.md#account-tenant-identifier-boundary), which distinguishes canonical public/direct-text scopes and JOIN results from legacy numeric runtime reads. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving) records current implementation and focused proof. Full token-profile qualification and production authorization custody remain separate. -The caller verifier, lease owner and certificate-guarded seven-method receiver remain manually composed and unregistered. Their [lease contract](./api-contracts.md#canonical-public-production-new-admission-lease-source) preserves immutable original attempts and ACKs, with full tenant-source guards for new acquisition and first finalization and the separate current-caller/global-Account/token guards for exact metadata and cleanup recovery. Current-token verification alone grants no admission. Forward V1014 stores separate immutable resolution of a retained unknown-decision abort without rewriting its original terminal evidence. Forward V1015 adds a disjoint never-admitted negative resolution, retaining the original transition, abandonment and candidate/closure digests without a binding decision; the linked lease contract owns its exact selectors and authority. Focused actual Account–Game Session composition covers that exact recovery and restart boundary; upstream source custody and test PKI remain controlled. Broader token-retirement and orphan-cleanup delivery, default registration and admitted binding remain unqualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) owns the implementation and proof details. +The caller verifier, lease owner and certificate-guarded seven-method receiver remain manually composed and unregistered. Their [lease contract](./api-contracts.md#canonical-public-production-new-admission-lease-source) preserves immutable original attempts and ACKs, with full tenant-source guards for new acquisition and first finalization and the separate current-caller/global-Account/token guards for exact metadata and cleanup recovery. The explicit paid NEW composition reuses existing hosting storage and its current reader on each exact enlisted connection; no new schema or default registration is introduced. Current-token verification alone grants no admission. Forward V1014 stores separate immutable resolution of a retained unknown-decision abort without rewriting its original terminal evidence. Forward V1015 adds a disjoint never-admitted negative resolution, retaining the original transition, abandonment and candidate/closure digests without a binding decision; the linked lease contract owns its exact selectors and authority. Focused actual Account–Game Session composition covers that exact recovery and restart boundary; upstream source custody and test PKI remain controlled. Broader token-retirement and orphan-cleanup delivery, default registration and admitted binding remain unqualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) owns the implementation and proof details. The selected-recipient intake source prepares distinct Entity/Automation source reservations and finalized authorizations, retained source-writer exclusion, and exact terminal settlement. Expired preliminary recovery pages use a caller-held `(expiry epoch second, operation UUID)` keyset cursor that advances across every examined row, including invalid rows and candidates whose abort does not commit; a caller continues while a cursor is returned and starts a fresh sweep only after an empty page. Prepared final authorization and terminal migrations V1008–V1010 follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002, while preserving prior protection/disposal guards. These components remain unregistered and unqualified; the [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation) owns current proof, qualification limits and remaining dependencies. 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 590fce0e34..c9888197af 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -190,6 +190,8 @@ The unregistered receiver includes explicit original closure under the existing ### Canonical NEW admission components +The Account NEW source now prepares an explicit paid-hosting composition alongside DEMO. Account selects the current source head, prepares the existing hosting owner's exact fence in an Account-first writable SERIALIZABLE transaction, observes the real bounded Stripe SDK outside SQL, then reconstructs that owner on the decisive transaction's exact connection and rereads its current receipt. Opaque owner-bound preparation/observation carries no caller-selected source authority; missing paid composition, changed heads, unresolved provider facts and expired authority fail closed without DEMO fallback. The original lease retains the same five source subtrees and is additionally capped at paid authority expiry. First finalization rereads complete paid authority through the original physical-COMMIT executor and exact-compares the original lease; metadata, cleanup and terminal receipt recovery retain their narrower current-caller checks. The [canonical session contract](../../architecture/system-architecture-session-behavior.md#canonical-public-production-new-admission) remains normative. Seven new PostgreSQL source/composition definitions cover actual owner reads, missing composition/observation, no provider read in SQL, provider disagreement/expiry, changed heads, authenticated acquisition/finalization/recovery and writer exclusion through physical COMMIT. On the local paid-source postimage over baseline `cee9af5e75f2f84140efdc6f9e902794cf61986e`, the focused gate passes all 87 selected unit cases with zero failures, errors or skips: four lease-owner, 26 original-COMMIT executor, 40 ACK-receipt executor, eleven hosting-repository and six hosting-policy cases. Full integration compilation includes the new paid fixture; enabled main/test/integration SpotBugs, Java formatting and Markdown lint pass. The initial gate failed on one unnecessary new SpotBugs suppression, removed before the successful rerun. Physical PostgreSQL/Redis execution remains unrun because Docker is unavailable, and external link checking remains unrun. Compilation and static analysis do not replace physical proof. Controlled provider transport, reverse Game Session evidence and test custody do not establish live Stripe, an admitted binding, production registration or available `PLAY`/`LOOK`. + Local negative-continuation preparation retains irreversible original-candidate abandonment, a persistent non-admitting Redis closure, separately authenticated Account negative resolution, and genuine ordinary-local or installed frozen-cohort issuer release/retirement. R1044 executes 33 selected Game Session cases (30 pass, two historical-fixture failures and one PostgreSQL startup failure) and nine Account cases (five pass, two ordinary terminal-retirement failures, one inaccessible test-handle failure and one Redis startup failure). The run's failed aggregate remains retained; later corrections are qualified by the separately attributed receiving results below. Pre-anchor or superseded issued work without an installed revision owner remains unresolved and non-admitting under Gameplay ownership. Existing holds authorize no old-key cleanup, invented ordinary registration or Redis-absence proof; this does not waive the separately held recovery scope. Implementing that held category requires an exact authority/contract proposal. Controlled qualification, upstream source and test PKI do not establish production custody, registration, activation or gameplay admission. For the PLAYER_CREATED correction, R1069 passed 67/68 selected cases; its single failure was an initial Redis connection refusal of unknown cause. R1074 then passed 122/126, with three Account negative-composition failures because V1051 omitted inherited `NEVER_DISPATCHED` branches and one World cleanup failure that could mask the primary exception; the underlying connection-refusal cause remains unknown. Corrected V1051 retains the inherited statuses and branch without editing source-parent migrations. On corrected source `e93aac69277af1fe39afe196db1546cf5eb4737a`, R1077 separately passes all 15 selected cases (eight Game Session region-owner, three Account final-admission, three Account negative-composition and one World receipt case), plus selected static, generation and documentation checks; source hashes are stable and Spotless made no formatter changes. R1082 is local proof only, with its two-file test preparation subsequently retained at `c8f16db50e27a754e1d80a94d09c8d8f32f2ee4f` on genuine parent `d2e3a21a31419680e68ab2da6ea7e808e4efd83c`: against that V1050.4 parent, before introducing corrected V1051, both ordinary and installed parameter cases pass while preserving release/retirement records, old columns and `xmin`, Flyway history/checksums, issuer/closure Redis and exact retry after Account restart. R1079 remains a failed pre-migration proof setup because it repeated preparation after cleanup and supplies no migration credit. R1086 subsequently passes all 31 selected receiving cases on reconciled source `b7143cf062699bca230f4c2cbec03f9da651a380`: Account handler and bounded-readback units, Game Session authenticated-session and candidate units, three actual Account final-admission compositions and both Entity namespace concurrency/scope-refusal regressions. All selected generation, enabled static analysis, formatting and documentation checks pass, with no service formatter delta. R1089 separately passes 26 native executions on the receiving child (eight final-owner and 18 parameterized Account definitive-abort cases), including the new explicit REQUIRED-delete refusal. Positive-source R1092 subsequently passes 26 executions (13 reader units, four reader-service units and nine native final-owner cases) after separating clock unavailability from retained-source conflict and tightening every refusal assertion. Its new native case confirms the existing committed-receipt delete guard, unchanged retained state through clock lag and successful readback when the clock catches up; R1093 separately executes all 12 selected descendant native cases (nine final-owner and three actual Account compositions) successfully, with selected static analysis and no source/formatter changes. Its aggregate remains failed because Markdown lint rejected the added HTML link anchor; the Markdown-heading correction and documentation recovery retain separate attribution. These separate results do not establish an all-126 clean aggregate, current CI, production/default registration, PKI custody or activation. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java index 021b5574be..9bdd449bae 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java @@ -11,6 +11,8 @@ import java.util.UUID; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; @@ -29,11 +31,11 @@ * admission. * *

The caller enlists the exact supplied DSLContext in its writable SERIALIZABLE transaction. - * This component creates no transaction, performs no writes or network calls, and owns no lease. It - * reads current Account membership, tenant entitlement, and the active SQL token fence under the - * canonical Account-first lock order. The caller verifier remains responsible for JWT/JWKS and - * exact Redis currentness outside SQL; this source cannot re-prove either remote registry state or - * a published gameplay target. + * This component creates no transaction, performs no writes, and owns no lease. Its SQL phases read + * current Account membership, tenant entitlement, and the active SQL token fence under the + * canonical Account-first lock order; its prepared handle observes the provider only outside SQL. + * The caller verifier remains responsible for JWT/JWKS and exact Redis currentness outside SQL; + * this source cannot re-prove either remote registry state or a published gameplay target. * *

The returned membership snapshot is complete current Account evidence. The Current result can * produce the five unchanged Account source subtrees for a lease and compare them against an @@ -43,9 +45,9 @@ * global issuer/account authority and ACTIVE token checks but deliberately does not require the * original tenant membership or entitlement baseline to remain unchanged. * - *

The NEW lease projection currently supports explicit DEMO entitlements only. Paid current - * tenant authority remains readable by the generic membership source, but this DEMO-shaped lease - * projection refuses paid hosting rather than decoding it as DEMO or consulting a provider in SQL. + *

Paid sources require an opaque preparation and actual provider observation from the concrete + * hosting owner composition. Its receipt is revalidated on this exact SQL connection. A missing + * paid composition or changed selected head never falls back to DEMO. */ public final class AccountGameplayAdmissionCurrentSources { private static final String ACCOUNT_ISSUER = GameSessionAccountDelegationProfile.ISSUER; @@ -63,18 +65,21 @@ public final class AccountGameplayAdmissionCurrentSources { private final AccountTenantAuthorityEventRepository tenantAuthorityEvents; private final AccountTenantEntitlementOutboxRepository tenantEntitlementOutbox; private final AccountGameplayDelegationIssuanceRepository issuance; + private final String workloadNamespace; private AccountGameplayAdmissionCurrentSources( DSLContext dsl, AccountCanonicalRuntimeMembershipSnapshotRepository membershipSnapshots, AccountTenantAuthorityEventRepository tenantAuthorityEvents, AccountTenantEntitlementOutboxRepository tenantEntitlementOutbox, - AccountGameplayDelegationIssuanceRepository issuance) { + AccountGameplayDelegationIssuanceRepository issuance, + String workloadNamespace) { this.dsl = Objects.requireNonNull(dsl); this.membershipSnapshots = Objects.requireNonNull(membershipSnapshots); this.tenantAuthorityEvents = Objects.requireNonNull(tenantAuthorityEvents); this.tenantEntitlementOutbox = Objects.requireNonNull(tenantEntitlementOutbox); this.issuance = Objects.requireNonNull(issuance); + this.workloadNamespace = workloadNamespace; } /** @@ -127,7 +132,43 @@ static AccountGameplayAdmissionCurrentSources bind( new AccountGameplayDelegationIssuanceRepository(exactDsl, sourceEvidence, evidenceBundles); return new AccountGameplayAdmissionCurrentSources( - exactDsl, membershipSnapshots, tenantAuthorityEvents, tenantEntitlementOutbox, issuance); + exactDsl, + membershipSnapshots, + tenantAuthorityEvents, + tenantEntitlementOutbox, + issuance, + configuredWorkloadNamespace); + } + + /** Captures only Account-owned selectors/fences; the provider read follows outside SQL. */ + Prepared prepareCurrentPublicProductionNew( + UUID tenantId, + UUID originalTokenJti, + CommittedCandidateVerificationData candidate, + AccountGameplayAdmissionPaidSource paidSource) { + UUID accountId = verifiedCallerAccountId(tenantId, originalTokenJti, candidate); + requireWritableSerializableAccountTransaction(); + + // The hosting lifecycle's lock order is Account -> customer -> instrument -> tenant owner -> + // subscription -> tenant generation. Complete its SQL preparation before membership/source + // reads lock tenant generations, avoiding a reverse edge when a joiner differs from the payer. + AccountGameplayAdmissionPaidSource.Preparation paidPreparation = null; + if (paidSource != null + && paidSource.hasCurrentPaidSourceCandidate(dsl, workloadNamespace, tenantId)) { + lockRequiredAccountsBeforeTenantSources(dsl, tenantId, accountId); + paidPreparation = paidSource.prepare(dsl, workloadNamespace, tenantId); + } else { + lockExactAccountFirst(accountId); + } + CallerSources caller = readCallerSources(tenantId, originalTokenJti, candidate, accountId); + SourceSelection selected = caller.selection(); + if (selected.kind() == SourceKind.PAID_HOSTING) { + if (paidPreparation == null) throw unavailable(); + } else { + if (paidPreparation != null) throw unavailable(); + requireCurrentDemo(caller.snapshot(), tenantId, selected.checkpoint()); + } + return new Prepared(selected, paidSource, paidPreparation); } /** @@ -141,35 +182,80 @@ Current readCurrentPublicProductionNew( UUID targetTenantId, UUID expectedOriginalTokenJti, CommittedCandidateVerificationData expectedCommittedCandidate) { - Objects.requireNonNull(expectedCommittedCandidate, "Verified caller candidate is required"); - requireNonNilUuid(targetTenantId, "Canonical target tenant UUID"); - requireV4Uuid(expectedOriginalTokenJti, "Expected original token JTI"); + return readCurrentPublicProductionNew( + targetTenantId, expectedOriginalTokenJti, expectedCommittedCandidate, null); + } - var expectedIdentity = expectedCommittedCandidate.identity(); - UUID accountId = expectedIdentity.accountId(); - requireNonNilUuid(accountId, "Verified caller Account UUID"); - if (!expectedOriginalTokenJti.equals(expectedIdentity.tokenJti()) - || !accountId.equals(expectedCommittedCandidate.authoritySnapshot().accountId())) { - throw unavailable(); + Current readCurrentPublicProductionNew( + UUID targetTenantId, + UUID expectedOriginalTokenJti, + CommittedCandidateVerificationData expectedCommittedCandidate, + Observed observed) { + UUID accountId = + verifiedCallerAccountId( + targetTenantId, expectedOriginalTokenJti, expectedCommittedCandidate); + requireWritableSerializableAccountTransaction(); + + // Reacquire the complete hosting lifecycle lock set before taking membership/tenant source + // generations. The post-lock source selector below still verifies that this receipt is the + // exact current paid source for the requested tenant. + AccountHostingSubscriptionCurrentReceipt paidReceipt = null; + if (observed != null && observed.paidSource != null && observed.paidObservation != null) { + lockRequiredAccountsBeforeTenantSources(dsl, targetTenantId, accountId); + paidReceipt = + observed.paidSource.readCurrent(dsl, workloadNamespace, observed.paidObservation); + } else { + lockExactAccountFirst(accountId); } + CallerSources caller = + readCallerSources( + targetTenantId, expectedOriginalTokenJti, expectedCommittedCandidate, accountId); + SourceSelection selected = caller.selection(); + if (observed != null + && (selected.kind() != observed.selected.kind() + || !observed.selected.matches(selected.checkpoint()))) throw unavailable(); + Long sourceValidUntilMs = null; + if (selected.kind() == SourceKind.PAID_HOSTING) { + if (paidReceipt == null) throw unavailable(); + var receipt = paidReceipt; + TenantAuthorityEventV1Codec.Event event = receipt.tenantAuthorityEvent(); + if (!targetTenantId.equals(receipt.current().tenantId()) + || !selected.matches(event) + || !receipt.receiptRequestId().equals(event.requestId()) + || !receipt.billingEventId().equals(event.tenantBillingEventId()) + || !receipt.billingEventDigest().equals(event.tenantBillingEventDigest()) + || receipt.tenantBillingSequence() != event.tenantBillingSequence() + || !receipt.gameplayAvailable() + || !receipt.allowNewGameplayBindings()) { + throw unavailable(); + } + requireSupportedPublicTenantTuple( + caller.snapshot(), targetTenantId, event, receipt.tenantBillingSequence()); + sourceValidUntilMs = receipt.validUntil().toEpochMilli(); + } else { + if (paidReceipt != null) throw unavailable(); + requireCurrentDemo(caller.snapshot(), targetTenantId, selected.checkpoint()); + } + return new Current(caller.snapshot(), caller.candidate(), sourceValidUntilMs); + } - requireWritableSerializableAccountTransaction(); - lockExactAccountFirst(accountId); + private void requireCurrentDemo( + Snapshot snapshot, UUID tenantId, TenantAuthorityEventV1Codec.Event authorityEvent) { + DemoTenantEntitlementEventV1Codec.Event event = + readExactCurrentTenantEntitlement(tenantId, authorityEvent); + requireSupportedPublicTenantTuple( + snapshot, tenantId, authorityEvent, event.tenantBillingSequence()); + if (!event.gameplayAvailable() || !event.allowNewGameplayBindings()) throw unavailable(); + } + private CallerSources readCallerSources( + UUID targetTenantId, + UUID expectedOriginalTokenJti, + CommittedCandidateVerificationData expectedCommittedCandidate, + UUID accountId) { Snapshot snapshot = membershipSnapshots.readCurrent(accountId, targetTenantId); var selected = tenantAuthorityEvents.readCurrentSourceSelection(targetTenantId); - if (selected.kind() != AccountTenantAuthorityEventRepository.SourceKind.NON_PAID_DEMO) { - throw unavailable(); - } - TenantAuthorityEventV1Codec.Event authorityEvent = selected.checkpoint(); - DemoTenantEntitlementEventV1Codec.Event typedTenantEvent = - readExactCurrentTenantEntitlement(targetTenantId, authorityEvent); - requireCurrentActiveMembership(snapshot, accountId, targetTenantId); - requireSupportedPublicTenantTuple(snapshot, targetTenantId, authorityEvent, typedTenantEvent); - if (!typedTenantEvent.gameplayAvailable() || !typedTenantEvent.allowNewGameplayBindings()) { - throw unavailable(); - } CommittedCandidateVerificationData currentCommittedCandidate = issuance @@ -181,7 +267,25 @@ Current readCurrentPublicProductionNew( } requireCandidateAuthorityMatchesSnapshot(currentCommittedCandidate, snapshot, accountId); - return new Current(snapshot, typedTenantEvent, currentCommittedCandidate); + return new CallerSources(snapshot, selected, currentCommittedCandidate); + } + + private UUID verifiedCallerAccountId( + UUID tenantId, + UUID expectedOriginalTokenJti, + CommittedCandidateVerificationData expectedCommittedCandidate) { + Objects.requireNonNull(expectedCommittedCandidate, "Verified caller candidate is required"); + requireNonNilUuid(tenantId, "Canonical target tenant UUID"); + requireV4Uuid(expectedOriginalTokenJti, "Expected original token JTI"); + + var expectedIdentity = expectedCommittedCandidate.identity(); + UUID accountId = expectedIdentity.accountId(); + requireNonNilUuid(accountId, "Verified caller Account UUID"); + if (!expectedOriginalTokenJti.equals(expectedIdentity.tokenJti()) + || !accountId.equals(expectedCommittedCandidate.authoritySnapshot().accountId())) { + throw unavailable(); + } + return accountId; } /** @@ -374,7 +478,7 @@ private static void requireSupportedPublicTenantTuple( Snapshot snapshot, UUID tenantId, TenantAuthorityEventV1Codec.Event authorityEvent, - DemoTenantEntitlementEventV1Codec.Event typedTenantEvent) { + long tenantBillingSequence) { String tenantKey = tenantId.toString(); AuthorityTuple tuple = snapshot.authorityTuple(); Map expectedTenantGeneration = @@ -384,7 +488,7 @@ private static void requireSupportedPublicTenantTuple( TenantBillingCutoff expectedBillingCutoff = new TenantBillingCutoff( Long.toString(authorityEvent.tenantAuthorityGeneration()), - Long.toString(typedTenantEvent.tenantBillingSequence()), + Long.toString(tenantBillingSequence), authorityEvent.outboxStreamKey(), Long.toString(authorityEvent.outboxSequence())); Map expectedBillingCutoffs = @@ -511,12 +615,12 @@ private static IllegalStateException unavailable() { /** Complete, immutable source result; it contains neither a JWT nor registry bytes. */ record Current( Snapshot snapshot, - DemoTenantEntitlementEventV1Codec.Event typedTenantEvent, - CommittedCandidateVerificationData currentCommittedCandidate) { + CommittedCandidateVerificationData currentCommittedCandidate, + Long sourceValidUntilMs) { Current { Objects.requireNonNull(snapshot); - Objects.requireNonNull(typedTenantEvent); Objects.requireNonNull(currentCommittedCandidate); + if (sourceValidUntilMs != null && sourceValidUntilMs <= 0L) throw unavailable(); } /** Returns exactly the five immutable, current-source subtrees used by lease capture. */ @@ -531,6 +635,9 @@ void requireMatchesOriginalLease(AccountGameplayAdmissionLeaseEvidence originalL != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING) { throw unavailable(); } + if (sourceValidUntilMs != null + && Long.parseLong((String) originalLease.carrier().get("expiresAt")) > sourceValidUntilMs) + throw unavailable(); Map carrier = originalLease.carrier(); Object scopeValue = carrier.get("bindingScope"); if (!(scopeValue instanceof Map bindingScope) @@ -545,4 +652,46 @@ void requireMatchesOriginalLease(AccountGameplayAdmissionLeaseEvidence originalL } } } + + private record CallerSources( + Snapshot snapshot, SourceSelection selection, CommittedCandidateVerificationData candidate) {} + + static final class Prepared { + private final SourceSelection selected; + private final AccountGameplayAdmissionPaidSource paidSource; + private final AccountGameplayAdmissionPaidSource.Preparation paidPreparation; + + private Prepared( + SourceSelection selected, + AccountGameplayAdmissionPaidSource paidSource, + AccountGameplayAdmissionPaidSource.Preparation paidPreparation) { + this.selected = selected; + this.paidSource = paidSource; + this.paidPreparation = paidPreparation; + } + + Observed observeOutsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); + return new Observed( + selected, + paidSource, + paidPreparation == null ? null : paidSource.observe(paidPreparation)); + } + } + + static final class Observed { + private final SourceSelection selected; + private final AccountGameplayAdmissionPaidSource paidSource; + private final AccountGameplayAdmissionPaidSource.Observation paidObservation; + + private Observed( + SourceSelection selected, + AccountGameplayAdmissionPaidSource paidSource, + AccountGameplayAdmissionPaidSource.Observation paidObservation) { + this.selected = selected; + this.paidSource = paidSource; + this.paidObservation = paidObservation; + } + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwner.java index 7ee682d41a..acdb833230 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwner.java @@ -68,12 +68,23 @@ public final class AccountGameplayAdmissionLeaseOwner { private final String workloadNamespace; private final AccountGameplayAdmissionOriginalCommitExecutor originalCommitExecutor; private final AccountGameplayAdmissionOriginalAckReceiptCommitExecutor receiptExecutor; + private final AccountGameplayAdmissionPaidSource paidSource; public AccountGameplayAdmissionLeaseOwner( AccountGameplayAdmissionCallerVerifier callerVerifier, CanonicalGameplayAdmissionDecisionReadClient decisionReadClient, String workloadNamespace, DataSource dataSource) { + this(callerVerifier, decisionReadClient, workloadNamespace, dataSource, null); + } + + /** Explicit paid source composition; the four-argument form remains DEMO-only. */ + public AccountGameplayAdmissionLeaseOwner( + AccountGameplayAdmissionCallerVerifier callerVerifier, + CanonicalGameplayAdmissionDecisionReadClient decisionReadClient, + String workloadNamespace, + DataSource dataSource, + AccountGameplayAdmissionPaidSource paidSource) { this.callerVerifier = Objects.requireNonNull(callerVerifier, "Account caller verifier required"); this.decisionReadClient = @@ -83,6 +94,7 @@ public AccountGameplayAdmissionLeaseOwner( } this.workloadNamespace = workloadNamespace; this.dataSource = Objects.requireNonNull(dataSource, "Account DataSource required"); + this.paidSource = paidSource; originalCommitExecutor = new AccountGameplayAdmissionOriginalCommitExecutor(dataSource); receiptExecutor = new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(dataSource); } @@ -148,7 +160,8 @@ public AccountGameplayAdmissionLeaseResponse acquire( expectedTarget, request.bindingGeneration(), current.currentSources().leaseSourceFields(), - caller.identity().expiresAtEpochSecond()); + caller.identity().expiresAtEpochSecond(), + current.currentSources().sourceValidUntilMs()); return repository.beginPending(evidence); }); @@ -182,7 +195,7 @@ public AccountGameplayAdmissionLeaseResponse finalizeLease( // Game Session is allowed to have advanced the decision beyond PROVISIONAL after the original // physical COMMIT, so do this narrowly fenced read before asking for a fresh provisional view. AccountGameplayAdmissionLeaseOperation retainedBeforeRemoteReads = - readExactForFinalization(caller, lease); + readExactWithCurrentCallerOnly(caller, lease); if (retainedBeforeRemoteReads.state() == AccountGameplayAdmissionLeaseOperation.State.COMMITTED) { OriginalAckReceiptEvidence receipt = @@ -220,7 +233,8 @@ public AccountGameplayAdmissionLeaseResponse finalizeLease( throw unavailable(); } - AccountGameplayAdmissionLeaseOperation beforeCommit = readExactForFinalization(caller, lease); + AccountGameplayAdmissionLeaseOperation beforeCommit = + readExactWithCurrentCallerOnly(caller, lease); if (beforeCommit.state() == AccountGameplayAdmissionLeaseOperation.State.COMMITTED) { OriginalAckReceiptEvidence receipt = @@ -247,9 +261,14 @@ public AccountGameplayAdmissionLeaseResponse finalizeLease( // through this executor to reconstruct a late acknowledgement. OriginalCommitAcknowledgement acknowledgement; try { + var observed = prepareCurrentSources(caller, tenantId(lease)); acknowledgement = originalCommitExecutor.executeWithCurrentSources( - lease, request.bindingDecisionId(), workloadNamespace, caller.currentCandidate()); + lease, + request.bindingDecisionId(), + workloadNamespace, + caller.currentCandidate(), + observed); } catch (RuntimeException unavailable) { throw unavailable(); } @@ -693,7 +712,8 @@ private AccountGameplayAdmissionLeaseEvidence buildOriginalEvidence( Target target, BigInteger bindingGeneration, Map currentSourceFields, - long tokenExpiryEpochSecond) { + long tokenExpiryEpochSecond, + Long sourceValidUntilMs) { Long databaseNow = dsl.fetchSingle("SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint") .get(0, Long.class); @@ -705,6 +725,7 @@ private AccountGameplayAdmissionLeaseEvidence buildOriginalEvidence( Math.min( Math.addExact(now, AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS), Math.multiplyExact(tokenExpiryEpochSecond, 1000L)); + if (sourceValidUntilMs != null) originalExpiry = Math.min(originalExpiry, sourceValidUntilMs); } catch (ArithmeticException overflow) { throw unavailable(); } @@ -749,12 +770,13 @@ private T withCurrentSources( Objects.requireNonNull(caller); Objects.requireNonNull(tenantId); try { + var observed = prepareCurrentSources(caller, tenantId); return inWritableSerializableTransaction(dsl -> { AccountGameplayAdmissionCurrentSources currentSources = AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace); var current = currentSources.readCurrentPublicProductionNew( - tenantId, caller.identity().tokenJti(), caller.currentCandidate()); + tenantId, caller.identity().tokenJti(), caller.currentCandidate(), observed); return operation.apply( new CurrentAccountOperation( dsl, current, new AccountGameplayAdmissionLeaseRepository(dsl))); @@ -766,6 +788,21 @@ private T withCurrentSources( } } + private AccountGameplayAdmissionCurrentSources.Observed prepareCurrentSources( + VerifiedCaller caller, UUID tenantId) { + if (paidSource == null) { + requireNoAmbientSql(); + return null; + } + var prepared = + inWritableSerializableTransaction(dsl -> + AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace) + .prepareCurrentPublicProductionNew( + tenantId, caller.identity().tokenJti(), caller.currentCandidate(), paidSource)); + requireNoAmbientSql(); + return prepared.observeOutsideSql(); + } + /** Exact non-admitting read after fresh current caller/global Account/token SQL proof. */ private AccountGameplayAdmissionLeaseOperation readExactWithCurrentCallerOnly( VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) { @@ -785,38 +822,6 @@ private AccountGameplayAdmissionLeaseOperation readExactWithCurrentCallerOnly( } } - /** - * Exact finalization lookup: terminal history needs only current caller proof, while PENDING - * still requires the complete current public-production tenant source tuple in this transaction. - */ - private AccountGameplayAdmissionLeaseOperation readExactForFinalization( - VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) { - try { - return inWritableSerializableTransaction(dsl -> { - AccountGameplayAdmissionCurrentSources currentSources = - AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace); - currentSources.requireCurrentAuthenticatedCallerOnly(caller.currentCandidate()); - AccountGameplayAdmissionLeaseRepository repository = - new AccountGameplayAdmissionLeaseRepository(dsl); - AccountGameplayAdmissionLeaseOperation operation = - repository - .readExact(lease) - .orElseThrow(AccountGameplayAdmissionLeaseOwner::unavailable); - if (operation.state() == AccountGameplayAdmissionLeaseOperation.State.PENDING) { - var current = - currentSources.readCurrentPublicProductionNew( - tenantId(lease), caller.identity().tokenJti(), caller.currentCandidate()); - current.requireMatchesOriginalLease(lease); - } - return operation; - }); - } catch (StatusRuntimeException failure) { - throw failure; - } catch (RuntimeException unavailable) { - throw unavailable(); - } - } - /** * Atomically records or replays the exact orphan obligation under fresh caller-only SQL proof. */ diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java index 09c5ecae8b..18ed6ab2d3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java @@ -54,6 +54,16 @@ OriginalCommitAcknowledgement executeWithCurrentSources( UUID decisionId, String configuredNamespace, CommittedCandidateVerificationData authenticatedCandidate) { + return executeWithCurrentSources( + evidence, decisionId, configuredNamespace, authenticatedCandidate, null); + } + + OriginalCommitAcknowledgement executeWithCurrentSources( + AccountGameplayAdmissionLeaseEvidence evidence, + UUID decisionId, + String configuredNamespace, + CommittedCandidateVerificationData authenticatedCandidate, + AccountGameplayAdmissionCurrentSources.Observed observed) { Objects.requireNonNull(evidence); if (evidence.leaseKind() != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING || evidence.carrier().containsKey("expectedOldBindingGeneration")) { @@ -64,7 +74,8 @@ OriginalCommitAcknowledgement executeWithCurrentSources( decisionId, new CurrentSourceScope( Objects.requireNonNull(configuredNamespace), - Objects.requireNonNull(authenticatedCandidate))); + Objects.requireNonNull(authenticatedCandidate), + observed)); } private OriginalCommitAcknowledgement execute( @@ -101,7 +112,8 @@ private OriginalCommitAcknowledgement execute( .readCurrentPublicProductionNew( UUID.fromString((String) scope.get("tenantId")), UUID.fromString((String) token.get("tokenJti")), - currentSources.authenticatedCandidate()); + currentSources.authenticatedCandidate(), + currentSources.observed()); current.requireMatchesOriginalLease(evidence); } var repository = new AccountGameplayAdmissionLeaseRepository(exactDsl); @@ -166,7 +178,9 @@ public String toString() { } private record CurrentSourceScope( - String configuredNamespace, CommittedCandidateVerificationData authenticatedCandidate) {} + String configuredNamespace, + CommittedCandidateVerificationData authenticatedCandidate, + AccountGameplayAdmissionCurrentSources.Observed observed) {} private record OriginalBinding( AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId, String finalizationXid) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionPaidSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionPaidSource.java new file mode 100644 index 0000000000..695e72b66d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionPaidSource.java @@ -0,0 +1,161 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.time.Clock; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Explicit, unregistered paid-source composition for Account's original NEW lease owner. + * + *

Only the genuine hosting owner reads a current receipt. Every SQL phase constructs that owner + * on the caller's exact enlisted DSLContext. The opaque preparation and observation retain their + * originating composition; neither a public receipt record nor raw provider data is an input. + * Provider observation runs only outside SQL. This component registers no route or provider write. + */ +public final class AccountGameplayAdmissionPaidSource { + private static final JsonMapper BILLING_HINT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final String BILLING_SCHEMA_VERSION = "account-hosting-subscription-event/v1"; + private final AccountHostingPlanCatalog plans; + private final Clock clock; + private final ReconciliationLimits limits; + private final AccountHostingSubscriptionLifecyclePolicy policy; + private final StripeHostingSubscriptionObserver observer; + private final String namespace; + private final boolean livemode; + + public AccountGameplayAdmissionPaidSource( + AccountHostingPlanCatalog plans, + Clock clock, + ReconciliationLimits limits, + AccountHostingSubscriptionLifecyclePolicy policy, + StripeHostingSubscriptionObserver observer, + String namespace, + boolean livemode) { + this.plans = Objects.requireNonNull(plans); + this.clock = Objects.requireNonNull(clock); + this.limits = Objects.requireNonNull(limits); + this.policy = Objects.requireNonNull(policy); + this.observer = Objects.requireNonNull(observer); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + this.livemode = livemode; + } + + Preparation prepare(DSLContext exactDsl, String expectedNamespace, UUID tenantId) { + requireNamespace(expectedNamespace); + return new Preparation(this, reader(exactDsl).prepareCurrentRead(tenantId)); + } + + /** + * Unlocked routing hint from the exact current tenant source head. The paid lifecycle owner locks + * its sources first, then the locked selector validates the complete current envelope. + */ + boolean hasCurrentPaidSourceCandidate( + DSLContext exactDsl, String expectedNamespace, UUID tenantId) { + requireNamespace(expectedNamespace); + Record source = + exactDsl.fetchOne( + "SELECT e.payload " + + "FROM account_tenant_authority_source_records h " + + "JOIN account_tenant_entitlement_outbox_events e " + + "ON e.tenant_uuid = h.tenant_uuid " + + "AND e.tenant_billing_sequence = h.tenant_billing_sequence " + + "AND e.request_id = h.last_request_id " + + "AND e.event_id = h.tenant_billing_event_id " + + "AND e.event_digest = h.tenant_billing_event_digest " + + "WHERE h.tenant_uuid = ?", + tenantId); + if (source == null) return false; + byte[] payload = source.get("payload", byte[].class); + if (payload == null || payload.length == 0 || payload.length > 32768) return false; + try { + JsonNode envelope = BILLING_HINT_JSON.readTree(payload); + return envelope != null + && BILLING_SCHEMA_VERSION.equals(envelope.path("schemaVersion").asText()); + } catch (RuntimeException unreadableHint) { + return false; + } + } + + Observation observe(Preparation preparation) { + if (preparation == null + || preparation.owner != this + || TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Paid NEW observation requires no ambient Account SQL"); + } + return new Observation(preparation, observer.observe(preparation.fence.binding())); + } + + AccountHostingSubscriptionCurrentReceipt readCurrent( + DSLContext exactDsl, String expectedNamespace, Observation observation) { + requireNamespace(expectedNamespace); + if (observation == null || observation.preparation.owner != this) { + throw new IllegalStateException("Original paid NEW source observation required"); + } + var receipt = reader(exactDsl).readCurrent(observation.preparation.fence, observation.result); + Instant now = clock.instant(); + if (receipt.evaluatedAt() == null + || receipt.validUntil() == null + || now.isBefore(receipt.evaluatedAt()) + || !now.isBefore(receipt.validUntil())) { + throw new IllegalStateException("Current paid NEW source has expired"); + } + return receipt; + } + + private AccountHostingSubscriptionLifecycleRepository reader(DSLContext exactDsl) { + return new AccountHostingSubscriptionLifecycleRepository( + exactDsl, + new AccountSubscriptionIntentRepository(exactDsl, plans), + clock, + limits, + policy, + namespace, + livemode); + } + + private void requireNamespace(String expectedNamespace) { + if (!namespace.equals(expectedNamespace)) { + throw new IllegalStateException("Exact Account paid-source namespace required"); + } + } + + static final class Preparation { + private final AccountGameplayAdmissionPaidSource owner; + private final ReadFence fence; + + private Preparation(AccountGameplayAdmissionPaidSource owner, ReadFence fence) { + this.owner = owner; + this.fence = Objects.requireNonNull(fence); + } + } + + static final class Observation { + private final Preparation preparation; + private final StripeHostingSubscriptionObserver.Result result; + + private Observation(Preparation preparation, StripeHostingSubscriptionObserver.Result result) { + this.preparation = preparation; + this.result = Objects.requireNonNull(result); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java index 41e4522c29..4e7d5f68e3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java @@ -78,6 +78,7 @@ public final class AccountOriginalNewBoundGameplayCredentialOwner { private final AccountGameplayDelegationTokenRegistry tokenRegistry; private final AccountResponseEnvelopeCryptography responseCryptography; private final AccountOriginalNewFinalAdmissionReadClient finalAdmissionReadClient; + private final AccountGameplayAdmissionPaidSource paidSource; private final Clock clock; private final SecureRandom secureRandom; @@ -98,6 +99,7 @@ public AccountOriginalNewBoundGameplayCredentialOwner( responseCryptography, clock, null, + null, new SecureRandom()); } @@ -120,6 +122,31 @@ public AccountOriginalNewBoundGameplayCredentialOwner( responseCryptography, clock, Objects.requireNonNull(finalAdmissionReadClient), + null, + new SecureRandom()); + } + + /** Explicit paid-source observation composition; absent final reader keeps confirmation held. */ + public AccountOriginalNewBoundGameplayCredentialOwner( + DataSource dataSource, + String workloadNamespace, + AccountGameplayAdmissionCallerVerifier callerVerifier, + AccountGameplayDelegationSigner signer, + AccountGameplayDelegationTokenRegistry tokenRegistry, + AccountResponseEnvelopeCryptography responseCryptography, + Clock clock, + AccountOriginalNewFinalAdmissionReadClient finalAdmissionReadClient, + AccountGameplayAdmissionPaidSource paidSource) { + this( + dataSource, + workloadNamespace, + callerVerifier, + signer, + tokenRegistry, + responseCryptography, + clock, + finalAdmissionReadClient, + Objects.requireNonNull(paidSource), new SecureRandom()); } @@ -141,6 +168,7 @@ public AccountOriginalNewBoundGameplayCredentialOwner( responseCryptography, clock, null, + null, secureRandom); } @@ -153,6 +181,7 @@ private AccountOriginalNewBoundGameplayCredentialOwner( AccountResponseEnvelopeCryptography responseCryptography, Clock clock, AccountOriginalNewFinalAdmissionReadClient finalAdmissionReadClient, + AccountGameplayAdmissionPaidSource paidSource, SecureRandom secureRandom) { this.dataSource = Objects.requireNonNull(dataSource, "Account DataSource is required"); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { @@ -165,6 +194,7 @@ private AccountOriginalNewBoundGameplayCredentialOwner( this.tokenRegistry = Objects.requireNonNull(tokenRegistry); this.responseCryptography = Objects.requireNonNull(responseCryptography); this.finalAdmissionReadClient = finalAdmissionReadClient; + this.paidSource = paidSource; this.clock = Objects.requireNonNull(clock); this.secureRandom = Objects.requireNonNull(secureRandom); } @@ -243,9 +273,12 @@ private IssuedOriginalNew issueChecked( throw unavailable(); } final Genesis exactGenesisForCommit = genesis; + AccountGameplayAdmissionCurrentSources.Observed currentObservation = + prepareCurrentOriginalSource(currentCaller, requestedLease); Genesis committed = inWritableSerializableTransaction(dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease); + SourceRead current = + readCurrentOriginalSource(dsl, currentCaller, requestedLease, currentObservation); requireSameOriginalOperation(initial.operation(), current.operation()); AccountOriginalNewBoundGameplayIssuanceRepository issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); @@ -347,9 +380,12 @@ public OriginalAdmissionConfirmation confirmOriginalFinalAdmission( AccountGameplayAdmissionOriginalAckReceipt receipt = receiptExecutor.read(requestedLease, beforeRead.operation().bindingDecisionId()); requireExactReceipt(receipt, beforeRead.operation(), requestedLease); + AccountGameplayAdmissionCurrentSources.Observed beforeGenesisObservation = + prepareCurrentOriginalSource(caller, requestedLease); Genesis beforeGenesis = inWritableSerializableTransaction(dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, caller, requestedLease); + SourceRead current = + readCurrentOriginalSource(dsl, caller, requestedLease, beforeGenesisObservation); requireSameOriginalOperation(beforeRead.operation(), current.operation()); Genesis stored = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) @@ -394,9 +430,12 @@ public OriginalAdmissionConfirmation confirmOriginalFinalAdmission( .hasSameOwnerEvidence(caller.currentCandidate(), currentCaller.currentCandidate())) { throw unavailable(); } + AccountGameplayAdmissionCurrentSources.Observed recoveryObservation = + prepareCurrentOriginalSource(currentCaller, requestedLease); Genesis recovered = inWritableSerializableTransaction(dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease); + SourceRead current = + readCurrentOriginalSource(dsl, currentCaller, requestedLease, recoveryObservation); requireSameOriginalOperation(beforeRead.operation(), current.operation()); AccountGameplayAdmissionOriginalAckReceipt durableReceipt = new AccountGameplayAdmissionOriginalAckReceiptRepository( @@ -441,10 +480,7 @@ dsl, new AccountGameplayAdmissionLeaseRepository(dsl)) throw unavailable(); } if (!expected.equals(finalReadback.anchors())) throw unavailable(); - long nowMillis = clock.millis(); - if (nowMillis <= 0L - || finalReadback.admissionAtMillis() > nowMillis - || nowMillis >= finalReadback.continuityExpiresAtMillis()) throw unavailable(); + requireCurrentFinalReadback(finalReadback); VerifiedCaller beforeActivationCaller = verifyCaller(presentedInitialGsACompactJwt, peer); if (!AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData @@ -472,9 +508,13 @@ dsl, new AccountGameplayAdmissionLeaseRepository(dsl)) stringObjectMap(beforeGenesis.authorityTupleCanonicalBytes()), stringStringMap(beforeGenesis.membershipVersionCanonicalBytes())); String confirmationDigest = confirmationDigest(finalReadback, activation); + AccountGameplayAdmissionCurrentSources.Observed confirmationObservation = + prepareCurrentOriginalSource(currentCaller, requestedLease); Genesis confirmed = inWritableSerializableTransaction(dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease); + SourceRead current = + readCurrentOriginalSource( + dsl, currentCaller, requestedLease, confirmationObservation); requireSameOriginalOperation(beforeRead.operation(), current.operation()); AccountGameplayAdmissionOriginalAckReceipt durableReceipt = new AccountGameplayAdmissionOriginalAckReceiptRepository( @@ -489,13 +529,18 @@ dsl, new AccountGameplayAdmissionLeaseRepository(dsl)) requireSameGenesisIdentity(beforeGenesis, exact); TokenIdentity tokenIdentity = originalNewIdentity(exact); new AccountGameplayTokenIdentityFenceRepository(dsl).requireActiveReadback(tokenIdentity); - return issuance.confirmFinalAdmission( - exact, - finalReadback.admissionAtMillis(), - finalReadback.continuityExpiresAtMillis(), - confirmationDigest); + requireCurrentFinalReadback(finalReadback); + Genesis written = + issuance.confirmFinalAdmission( + exact, + finalReadback.admissionAtMillis(), + finalReadback.continuityExpiresAtMillis(), + confirmationDigest); + requireCurrentFinalReadback(finalReadback); + return written; }); tokenRegistry.requireExactOriginalNewActiveRecord(confirmed); + requireCurrentFinalReadback(finalReadback); if (!confirmationDigest.equals(confirmed.confirmationReadbackSha256())) throw unavailable(); return new OriginalAdmissionConfirmation( confirmed.lineageId(), @@ -542,6 +587,13 @@ private static void requireActivationMatches( || activation.replicaAofCount() < 1L) throw unavailable(); } + private void requireCurrentFinalReadback(AuthenticatedFinalAdmissionReadback readback) { + long now = clock.millis(); + if (now <= 0L + || readback.admissionAtMillis() > now + || now >= readback.continuityExpiresAtMillis()) throw unavailable(); + } + private static String confirmationDigest( AuthenticatedFinalAdmissionReadback finalReadback, AccountGameplayDelegationRedisClient.OriginalNewActivationReadback activation) { @@ -615,8 +667,10 @@ private Genesis signAndPersistCandidate( byte[] exactRecord = recordBytes.clone(); byte[] exactEnvelope = envelopeBytes.clone(); try { + AccountGameplayAdmissionCurrentSources.Observed currentObservation = + prepareCurrentOriginalSource(caller, lease); return inWritableSerializableTransaction(dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, caller, lease); + SourceRead current = readCurrentOriginalSource(dsl, caller, lease, currentObservation); if (current.operation().state() != State.COMMITTED || !current.operation().bindingDecisionId().equals(receipt.bindingDecisionId())) { throw unavailable(); @@ -655,37 +709,9 @@ private OriginalNewCredential openCommittedResult( AccountGameplayAdmissionLeaseEvidence lease, AccountGameplayAdmissionOriginalAckReceipt receipt, Genesis expectedGenesis) { - SourceRead source = readCurrentOriginalSource(caller, lease); - requireExactReceipt(receipt, source.operation(), lease); - Genesis committed = - inWritableSerializableTransaction(dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, caller, lease); - requireSameOriginalOperation(source.operation(), current.operation()); - var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); - Genesis exact = issuance.readByLease(leaseId(lease)); - requireSameGenesisIdentity(expectedGenesis, exact); - if (exact.status() - != AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED) { - throw unavailable(); - } - var tokenIdentity = - new TokenIdentity( - exact.accountId(), - exact.lineageId(), - exact.requestId(), - exact.tokenHash(), - exact.tokenJti(), - exact.notBeforeEpochSecond(), - exact.tokenGeneration(), - exact.issuanceFence(), - SourceKind.ORIGINAL_NEW); - new AccountGameplayTokenIdentityFenceRepository(dsl).requireActiveReadback(tokenIdentity); - return exact; - }); - - requireCommittedRegistryProjection(committed); - - return openFrozenCredentialResult(lease, receipt, source, committed); + CredentialOpen opened = readCredentialForOpen(caller, lease, receipt, expectedGenesis); + requireCommittedRegistryProjection(opened.genesis()); + return openFrozenCredentialResult(lease, receipt, opened.source(), opened.genesis()); } /** @@ -699,25 +725,33 @@ private OriginalNewCredential openFrozenCredentialForFinalAdmissionVerification( AccountGameplayAdmissionLeaseEvidence lease, AccountGameplayAdmissionOriginalAckReceipt receipt, Genesis expectedGenesis) { - SourceRead source = readCurrentOriginalSource(caller, lease); - requireExactReceipt(receipt, source.operation(), lease); - Genesis committed = - inWritableSerializableTransaction(dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, caller, lease); - requireSameOriginalOperation(source.operation(), current.operation()); - var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); - Genesis exact = issuance.readByLease(leaseId(lease)); - requireSameGenesisIdentity(expectedGenesis, exact); - if (exact.status() - != AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED) { - throw unavailable(); - } - new AccountGameplayTokenIdentityFenceRepository(dsl) - .requireActiveReadback(originalNewIdentity(exact)); - return exact; - }); + CredentialOpen opened = readCredentialForOpen(caller, lease, receipt, expectedGenesis); + return openFrozenCredentialResult(lease, receipt, opened.source(), opened.genesis()); + } - return openFrozenCredentialResult(lease, receipt, source, committed); + private CredentialOpen readCredentialForOpen( + VerifiedCaller caller, + AccountGameplayAdmissionLeaseEvidence lease, + AccountGameplayAdmissionOriginalAckReceipt receipt, + Genesis expectedGenesis) { + AccountGameplayAdmissionCurrentSources.Observed currentObservation = + prepareCurrentOriginalSource(caller, lease); + return inWritableSerializableTransaction(dsl -> { + SourceRead current = readCurrentOriginalSource(dsl, caller, lease, currentObservation); + // The owner already proved the immutable ACK's independent durability. Bind that exact + // proof and the token identity fence to the same fresh source used to verify the credential. + requireExactReceipt(receipt, current.operation(), lease); + requireSameOriginalOperation(receipt.operation(), current.operation()); + var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); + Genesis exact = issuance.readByLease(leaseId(lease)); + requireSameGenesisIdentity(expectedGenesis, exact); + if (exact.status() != AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED) { + throw unavailable(); + } + new AccountGameplayTokenIdentityFenceRepository(dsl) + .requireActiveReadback(originalNewIdentity(exact)); + return new CredentialOpen(current, exact); + }); } private OriginalNewCredential openFrozenCredentialResult( @@ -774,17 +808,42 @@ private OriginalNewCredential openFrozenCredentialResult( private SourceRead readCurrentOriginalSource( VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) { - return inWritableSerializableTransaction(dsl -> readCurrentOriginalSource(dsl, caller, lease)); + AccountGameplayAdmissionCurrentSources.Observed observed = + prepareCurrentOriginalSource(caller, lease); + return inWritableSerializableTransaction( + dsl -> readCurrentOriginalSource(dsl, caller, lease, observed)); + } + + private AccountGameplayAdmissionCurrentSources.Observed prepareCurrentOriginalSource( + VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) { + UUID targetTenantId = tenantId(lease); + if (paidSource == null) { + requireNoAmbientSql(); + return null; + } + AccountGameplayAdmissionCurrentSources.Prepared prepared = + inWritableSerializableTransaction(dsl -> + AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace) + .prepareCurrentPublicProductionNew( + targetTenantId, + caller.identity().tokenJti(), + caller.currentCandidate(), + paidSource)); + requireNoAmbientSql(); + return prepared.observeOutsideSql(); } private SourceRead readCurrentOriginalSource( - DSLContext dsl, VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) { + DSLContext dsl, + VerifiedCaller caller, + AccountGameplayAdmissionLeaseEvidence lease, + AccountGameplayAdmissionCurrentSources.Observed observed) { UUID tenantId = tenantId(lease); AccountGameplayAdmissionCurrentSources sourceReader = AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace); var current = sourceReader.readCurrentPublicProductionNew( - tenantId, caller.identity().tokenJti(), caller.currentCandidate()); + tenantId, caller.identity().tokenJti(), caller.currentCandidate(), observed); current.requireMatchesOriginalLease(lease); AccountGameplayAdmissionLeaseOperation operation = new AccountGameplayAdmissionLeaseRepository(dsl) @@ -1139,6 +1198,8 @@ private record SourceRead( } } + private record CredentialOpen(SourceRead source, Genesis genesis) {} + private record OpenedProtectedResult(byte[] compactJwtBytes, byte[] handleBytes) {} /** Actual original-admission anchors returned only by the Account-side confirmation hook. */ diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java index f86cbaed5f..60efdc0273 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java @@ -144,6 +144,13 @@ public List findByAccountUuids(List accountUuids) { return List.copyOf(accounts); } + /** Uses the same caller/payer Account lock order as paid NEW before JOIN source reads. */ + @Transactional(propagation = Propagation.MANDATORY) + public void lockCanonicalJoinAccounts(UUID tenantId, UUID callerAccountId) { + AccountGameplayAdmissionCurrentSources.lockRequiredAccountsBeforeTenantSources( + dsl, tenantId, callerAccountId); + } + /** Locks one exact Account UUID inside a writable owner transaction. */ @Transactional(propagation = Propagation.MANDATORY) public Optional findByAccountUuidForUpdate(UUID accountUuid) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 03536be46a..84d20a5a5b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -601,6 +601,8 @@ private CanonicalJoinPreparation prepareCanonicalJoin( }); return Objects.requireNonNull( joinTransactionTemplate.execute(status -> { + // Lock the caller and distinct payer before source selection or a hosting read. + accountRepository.lockCanonicalJoinAccounts(scope.tenantId(), scope.accountId()); lockCanonicalScopeAccount(scope); CanonicalJoinOperationEvidence operation = accountJoinOperationRepository @@ -634,6 +636,8 @@ private CanonicalJoinResult commitCanonicalJoin( StripeHostingSubscriptionObserver.Result observation) { return Objects.requireNonNull( joinTransactionTemplate.execute(status -> { + // The provider observation was outside SQL; reacquire the same Account lock order. + accountRepository.lockCanonicalJoinAccounts(scope.tenantId(), scope.accountId()); lockCanonicalScopeAccount(scope); requireCanonicalScopeFresh(consumers, scope); CanonicalJoinOperationEvidence lockedOperation = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index a9118d262b..34bf5c77a7 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -12,6 +12,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; import io.grpc.Context; import io.grpc.ManagedChannel; import io.grpc.MethodDescriptor; @@ -60,6 +61,7 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -89,6 +91,8 @@ import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.ProducerEvidence; import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; @@ -124,6 +128,8 @@ import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.AccountSecurityCutoff; import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; @@ -225,8 +231,7 @@ void positiveCurrentReadReturnsExactFiveSourcesAndOriginalCommitPreservesOwners( CommittedCandidateVerificationData.hasSameOwnerEvidence( independentCandidate, current.currentCommittedCandidate())) .isTrue(); - assertThat(current.typedTenantEvent().gameplayAvailable()).isTrue(); - assertThat(current.typedTenantEvent().allowNewGameplayBindings()).isTrue(); + assertThat(current.sourceValidUntilMs()).isNull(); assertThat(current.leaseSourceFields().keySet()) .containsExactlyInAnyOrder( "authorityTuple", @@ -255,6 +260,388 @@ void positiveCurrentReadReturnsExactFiveSourcesAndOriginalCommitPreservesOwners( .isEqualTo(current.leaseSourceFields()); } + @Test + void paidCurrentReadAndOriginalPhysicalCommitUseTheGenuineOwnerWithoutChangingSources() + throws Exception { + PaidFixture paid = newPaidFixture(null); + Fixture caller = paid.caller(); + var before = caller.sourceAndIssuanceImage(); + int reads = paid.hosting().transport().reads(); + var observed = paid.prepare().observeOutsideSql(); + var current = paid.read(observed); + assertThat(paid.hosting().transport().reads()).isEqualTo(reads + 1); + assertThat(current.snapshot().tenantId()).isEqualTo(paid.hosting().tenantId().toString()); + assertThat(current.sourceValidUntilMs()) + .isEqualTo(paid.hosting().clock().instant().plusSeconds(15).toEpochMilli()); + assertThat(caller.sourceAndIssuanceImage()).isEqualTo(before); + + var lease = caller.beginPendingAdmissionLease(current); + assertThat(Long.parseLong((String) lease.carrier().get("expiresAt"))) + .isLessThanOrEqualTo(current.sourceValidUntilMs()); + var ownerImage = caller.sourceAndIssuanceImage(); + UUID decisionId = UUID.randomUUID(); + var acknowledgement = + new AccountGameplayAdmissionOriginalCommitExecutor(caller.dataSource) + .executeWithCurrentSources( + lease, + decisionId, + TEST_NAMESPACE, + caller.committedCandidate, + paid.prepare().observeOutsideSql()); + assertThat(acknowledgement.evidence().canonicalJson()).isEqualTo(lease.canonicalJson()); + assertThat(caller.sourceAndIssuanceImage()).isEqualTo(ownerImage); + var receipt = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(caller.dataSource) + .confirm(acknowledgement); + assertThat(receipt.operation().state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.COMMITTED); + assertThat(receipt.operation().evidence().canonicalJson()).isEqualTo(lease.canonicalJson()); + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalCommitExecutor(caller.dataSource) + .executeWithCurrentSources( + lease, + decisionId, + TEST_NAMESPACE, + caller.committedCandidate, + paid.prepare().observeOutsideSql())) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void paidAdmissionLocksWalletBeforeTenantGenerationInBothSqlPhases() throws Exception { + PaidFixture paid = newPaidFixture(null); + Fixture caller = paid.caller(); + List sourceImageBefore = caller.sourceAndIssuanceImage(); + + var prepared = whileWalletInstrumentIsLockedBeforeTenantGeneration(paid, () -> paid.prepare()); + var observed = prepared.observeOutsideSql(); + var current = + whileWalletInstrumentIsLockedBeforeTenantGeneration(paid, () -> paid.read(observed)); + + assertThat(current.snapshot().tenantId()).isEqualTo(paid.hosting().tenantId().toString()); + assertThat(caller.sourceAndIssuanceImage()).isEqualTo(sourceImageBefore); + } + + @Test + void currentDemoHeadRemainsSelectedWhileSameTenantHasPendingHostingSubscription() + throws Exception { + Fixture caller = newFixture(null); + var hosting = CanonicalHostingSubscriptionTestFixture.create(caller.dataSource, TEST_NAMESPACE); + String authorizationDigest = "sha256:" + "a".repeat(64); + UUID authorizationOperation = UUID.randomUUID(); + var creator = + new FreshTenantCreatorEvidence( + 1, + caller.tenantEvidence, + hosting.accountUuid(), + authorizationOperation, + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, + caller.tenantEvidence, + hosting.accountUuid(), + authorizationOperation, + authorizationDigest)); + var owner = + caller.transaction.execute(status -> + new AccountInitialTenantBillingOwnerRepository(caller.dsl) + .establishInitial( + new AccountInitialTenantBillingOwnerRepository.InitialRequest( + UUID.randomUUID(), creator, UUID.randomUUID(), 1, true))); + var instrument = hosting.instrument(); + caller.transaction.execute(status -> + hosting + .intents() + .retainPending( + new AccountSubscriptionCreateRequest( + UUID.randomUUID(), + caller.tenantUuid, + new OwnerFence( + hosting.accountUuid(), owner.ownerVersion(), owner.ownerGeneration()), + "hosting", + instrument.instrumentUuid(), + instrument.rowVersion(), + new ProducerEvidence( + hosting.accountUuid(), UUID.randomUUID(), authorizationDigest), + null))); + + int providerReads = hosting.transport().reads(); + var prepared = + caller.inCurrentSources(sources -> + sources.prepareCurrentPublicProductionNew( + caller.tenantUuid, + caller.committedCandidate.identity().tokenJti(), + caller.committedCandidate, + hosting.admissionPaidSource())); + var observed = prepared.observeOutsideSql(); + var current = + caller.inCurrentSources(sources -> + sources.readCurrentPublicProductionNew( + caller.tenantUuid, + caller.committedCandidate.identity().tokenJti(), + caller.committedCandidate, + observed)); + + assertThat(current.sourceValidUntilMs()).isNull(); + assertThat(hosting.transport().reads()).isEqualTo(providerReads); + } + + @Test + void paidSourceWithoutItsConcreteCompositionOrObservationNeverFallsBackToDemo() throws Exception { + PaidFixture paid = newPaidFixture(null, true); + Fixture caller = paid.caller(); + var before = caller.sourceAndIssuanceImage(); + int reads = paid.hosting().transport().reads(); + assertThatThrownBy(() -> + caller.inCurrentSources(sources -> + sources.prepareCurrentPublicProductionNew( + paid.hosting().tenantId(), + caller.committedCandidate.identity().tokenJti(), + caller.committedCandidate, + null))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> paid.read(null)).isInstanceOf(IllegalStateException.class); + // Historical DEMO evidence for the exact paid tenant remains retained, not a fallback. + assertThat( + caller.dsl.fetchExists( + caller + .dsl + .selectOne() + .from("account_demo_tenant_entitlements") + .where( + org.jooq + .impl + .DSL + .field("tenant_uuid", UUID.class) + .eq(paid.hosting().tenantId())))) + .isTrue(); + assertThat(paid.hosting().transport().reads()).isEqualTo(reads); + assertThat(caller.sourceAndIssuanceImage()).isEqualTo(before); + assertThat(caller.leaseOperationCount()).isZero(); + } + + @Test + void paidObservationCannotRunInsideThePreparingAccountTransaction() throws Exception { + PaidFixture paid = newPaidFixture(null); + int reads = paid.hosting().transport().reads(); + assertThatThrownBy(() -> + paid.caller() + .inCurrentSources(sources -> + sources + .prepareCurrentPublicProductionNew( + paid.hosting().tenantId(), + paid.caller().committedCandidate.identity().tokenJti(), + paid.caller().committedCandidate, + paid.hosting().admissionPaidSource()) + .observeOutsideSql())) + .isInstanceOf(IllegalStateException.class); + assertThat(paid.hosting().transport().reads()).isEqualTo(reads); + } + + @Test + void paidObservationExpiryAndContradictoryProviderFactsCannotFinalizeTheOriginalLease() + throws Exception { + PaidFixture paid = newPaidFixture(null); + var current = paid.read(paid.prepare().observeOutsideSql()); + var lease = paid.caller().beginPendingAdmissionLease(current); + paid.hosting().providerStatus("past_due"); + var contradictory = paid.prepare().observeOutsideSql(); + assertThatThrownBy(() -> paid.read(contradictory)).isInstanceOf(IllegalStateException.class); + paid.hosting().providerStatus("active"); + var expired = paid.prepare().observeOutsideSql(); + paid.hosting().clock().advance(Duration.ofSeconds(15)); + var before = paid.caller().sourceAndIssuanceImage(); + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalCommitExecutor(paid.caller().dataSource) + .executeWithCurrentSources( + lease, + UUID.randomUUID(), + TEST_NAMESPACE, + paid.caller().committedCandidate, + expired)) + .isInstanceOf(IllegalStateException.class); + assertThat(paid.caller().readLeaseOperation(lease).state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.PENDING); + assertThat(paid.caller().sourceAndIssuanceImage()).isEqualTo(before); + } + + @Test + void paidHeadChangeDuringTheActualProviderReadRefusesThePreparedSourceAndOriginalLease() + throws Exception { + PaidFixture paid = newPaidFixture(null); + var current = paid.read(paid.prepare().observeOutsideSql()); + var lease = paid.caller().beginPendingAdmissionLease(current); + var prepared = paid.prepare(); + paid.hosting() + .transport() + .duringRead(() -> { + paid.hosting().clock().advance(Duration.ofSeconds(1)); + paid.refresh(); + }); + var observed = prepared.observeOutsideSql(); + var before = paid.caller().sourceAndIssuanceImage(); + assertThatThrownBy(() -> paid.read(observed)) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class) + .hasMessage("Pending claim owner/customer/instrument/subscription fence rejected"); + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalCommitExecutor(paid.caller().dataSource) + .executeWithCurrentSources( + lease, + UUID.randomUUID(), + TEST_NAMESPACE, + paid.caller().committedCandidate, + paid.prepare().observeOutsideSql())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "membership source tenantAuthorityGeneration current equality does not match its bound evidence"); + assertThat(paid.caller().readLeaseOperation(lease).evidence().canonicalJson()) + .isEqualTo(lease.canonicalJson()); + assertThat(paid.caller().readLeaseOperation(lease).state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.PENDING); + assertThat(paid.caller().sourceAndIssuanceImage()).isEqualTo(before); + } + + @Test + void authenticatedPaidOwnerCapsTheLeaseFinalizesOnceAndRecoversWithoutPaidAuthority() + throws Exception { + try (PhysicalRedisFixture redis = PhysicalRedisFixture.start()) { + PaidFixture paid = newPaidFixture(redis.client()); + Fixture caller = paid.caller(); + var identity = caller.committedCandidate.identity(); + var recovered = + caller.responseRecoveryOwner.recoverInitialLoginResponse( + identity.requestId(), + identity.accountId(), + new CallerIdentity(identity.callerWorkload(), identity.callerContextId())); + String jwt = new String(recovered.compactJwtBytes(), StandardCharsets.US_ASCII); + Candidate candidate = + candidateWithTenant(admissionCandidate(caller), paid.hosting().tenantId()); + UUID requestId = UUID.randomUUID(); + Target target = admissionTarget(candidate, UUID.randomUUID()); + var decisions = controlledPublishedTargetClient(candidate, target, requestId); + controlProvisionalDecisionRead(decisions, candidate, target); + var verifier = + new AccountGameplayAdmissionCallerVerifier( + caller.signerFixture.trustedJwksSource(), + caller.committedIssuanceOwner, + Clock.systemUTC()); + var owner = + new AccountGameplayAdmissionLeaseOwner( + verifier, + decisions, + TEST_NAMESPACE, + caller.dataSource, + paid.hosting().admissionPaidSource()); + var peer = GrpcPeerIdentity.parseUri(CALLER_WORKLOAD).orElseThrow(); + var acquire = + AccountGameplayAdmissionLeaseGrpcCodec.toAcquireRequest( + requestId, jwt, candidate, target, BigInteger.ONE); + var response = new AtomicReference(); + var before = caller.sourceAndIssuanceImageForAuthenticatedCommit(); + withPeer(peer, () -> response.set(owner.acquire(acquire))); + var lease = + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireResponse( + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest(acquire), + response.get()) + .originalLeaseEvidence(); + long evaluatedAt = Long.parseLong((String) lease.carrier().get("evaluatedAt")); + assertThat(Long.parseLong((String) lease.carrier().get("expiresAt"))) + .isEqualTo( + Math.min( + Math.min(evaluatedAt + 15_000L, identity.expiresAtEpochSecond() * 1000L), + paid.hosting().clock().instant().plusSeconds(15).toEpochMilli())); + byte[] leaseBytes = lease.canonicalJson().getBytes(StandardCharsets.UTF_8); + paid.hosting().providerStatus("unsupported"); + var read = AccountGameplayAdmissionLeaseGrpcCodec.toReadRequest(jwt, leaseBytes); + withPeer(peer, () -> response.set(owner.read(read))); + assertThat( + AccountGameplayAdmissionLeaseGrpcCodec.parseReadResponse( + AccountGameplayAdmissionLeaseGrpcCodec.parseReadRequest(read), response.get()) + .state()) + .isEqualTo(State.PENDING); + assertThatThrownBy(() -> withPeer(peer, () -> owner.acquire(acquire))) + .isInstanceOf(StatusRuntimeException.class); + UUID decisionId = UUID.randomUUID(); + var finalize = + AccountGameplayAdmissionLeaseGrpcCodec.toFinalizeRequest(jwt, leaseBytes, decisionId); + assertThatThrownBy(() -> withPeer(peer, () -> owner.finalizeLease(finalize))) + .isInstanceOf(StatusRuntimeException.class); + assertThat(caller.readLeaseOperation(lease).state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.PENDING); + + paid.hosting().providerStatus("active"); + withPeer(peer, () -> response.set(owner.finalizeLease(finalize))); + var committed = response.get(); + assertThat( + AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeResponse( + AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeRequest(finalize), + committed) + .state()) + .isEqualTo(State.COMMITTED); + assertThat(caller.readLeaseOperation(lease).evidence().canonicalJson()) + .isEqualTo(lease.canonicalJson()); + assertThat(caller.sourceAndIssuanceImageForAuthenticatedCommit()).isEqualTo(before); + + paid.hosting().providerStatus("unsupported"); + int providerReads = paid.hosting().transport().reads(); + var restartedWithoutPaidSource = + new AccountGameplayAdmissionLeaseOwner( + verifier, decisions, TEST_NAMESPACE, caller.dataSource); + withPeer(peer, () -> response.set(restartedWithoutPaidSource.finalizeLease(finalize))); + assertThat(response.get()).isEqualTo(committed); + assertThat(paid.hosting().transport().reads()).isEqualTo(providerReads); + } + } + + @Test + void paidLifecycleWriterWaitsForCurrentSourceLocksThroughOriginalPhysicalCommit() + throws Exception { + PaidFixture paid = newPaidFixture(null); + Fixture caller = paid.caller(); + var current = paid.read(paid.prepare().observeOutsideSql()); + var lease = caller.beginPendingAdmissionLease(current); + var observed = paid.prepare().observeOutsideSql(); + CountDownLatch reached = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + AtomicInteger originalBackendPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + var barrierSource = + holdOriginalCommitBeforePhysicalCommit( + caller.dataSource, reached, release, originalBackendPid); + try { + var commit = + executor.submit(() -> + new AccountGameplayAdmissionOriginalCommitExecutor(barrierSource) + .executeWithCurrentSources( + lease, + UUID.randomUUID(), + TEST_NAMESPACE, + caller.committedCandidate, + observed)); + assertThat(reached.await(5, TimeUnit.SECONDS)).isTrue(); + var writer = executor.submit(paid::refresh); + int blockedPid = + awaitBackendBlockedBy(caller.dsl, originalBackendPid.get(), 3, TimeUnit.SECONDS); + assertThat(blockedPid).isPositive().isNotEqualTo(originalBackendPid.get()); + assertThat(writer.isDone()).isFalse(); + release.countDown(); + assertThat(commit.get(5, TimeUnit.SECONDS).evidence().canonicalJson()) + .isEqualTo(lease.canonicalJson()); + writer.get(5, TimeUnit.SECONDS); + assertThat(caller.readLeaseOperation(lease).state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.COMMITTED); + assertThatThrownBy(() -> + paid.read(paid.prepare().observeOutsideSql()).requireMatchesOriginalLease(lease)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "membership source tenantAuthorityGeneration current equality does not match its bound evidence"); + } finally { + release.countDown(); + executor.shutdown(); + if (!executor.awaitTermination(5, TimeUnit.SECONDS)) executor.shutdownNow(); + } + } + @Test void authenticatedAccountOwnerAcquiresAndRetriesTheExactRecoveredAccountToken() throws Exception { try (PhysicalRedisFixture redis = PhysicalRedisFixture.start()) { @@ -1405,6 +1792,95 @@ private Fixture newFixture() throws Exception { return newFixture(null); } + PaidFixture newPaidFixture(AccountGameplayDelegationRedisClient redis) throws Exception { + return newPaidFixture(redis, false); + } + + private PaidFixture newPaidFixture( + AccountGameplayDelegationRedisClient redis, boolean retainSameTenantDemo) throws Exception { + Fixture caller = newFixture(redis); + var hosting = CanonicalHostingSubscriptionTestFixture.create(caller.dataSource, TEST_NAMESPACE); + UUID tenantId = hosting.tenantId(); + var source = + caller.transaction.execute(status -> caller.freshTenants.read(tenantId).orElseThrow()); + if (retainSameTenantDemo) { + var demoRequest = entitlementRequest(tenantId, source); + caller.transaction.execute(status -> caller.demoEntitlements.provision(demoRequest, source)); + } + hosting.withCheckoutDirectory(temporaryDirectory).completeFirstInvoice(); + var scope = canonicalJoinScope(caller.account.getAccountUuid(), tenantId); + var provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest()); + var scopes = + new AccountConnectScopeRepository( + caller.dsl, + new AccountTenantIdentityResolver( + mock(ApprovedLegacyTenantAssociationRepository.class), TEST_NAMESPACE), + caller.freshTenants); + String requestId = UUID.randomUUID().toString(); + String binding = "paid-new-player-" + UUID.randomUUID(); + caller.transaction.executeWithoutResult(status -> { + caller.generations.initialize( + AuthorityScope.membership(caller.account.getAccountUuid(), tenantId)); + scopes.insertCanonical(caller.account.getId(), scope, provenance); + caller.joinOperations.insertCanonicalIntent(requestId, scope, binding); + }); + var fence = + hosting + .transaction() + .execute(status -> hosting.lifecycleRepository().prepareCurrentRead(tenantId)); + var actual = hosting.observer().observe(fence.binding()); + caller.transaction.executeWithoutResult(status -> { + var receipt = hosting.lifecycleRepository().readCurrent(fence, actual); + caller.joinOperations.bindCanonicalPolicyEvidence( + requestId, scope, binding, receipt.allowPublicJoin(), receipt.entitlementVersion()); + caller.joinTerminal.commitPaidCanonicalFirstJoin( + scope, requestId, binding, hosting.lifecycleRepository(), fence, actual); + }); + return new PaidFixture(caller, hosting); + } + + record PaidFixture(Fixture caller, CanonicalHostingSubscriptionTestFixture.Fixture hosting) { + AccountGameplayAdmissionCurrentSources.Prepared prepare() { + return caller.inCurrentSources(sources -> + sources.prepareCurrentPublicProductionNew( + hosting.tenantId(), + caller.committedCandidate.identity().tokenJti(), + caller.committedCandidate, + hosting.admissionPaidSource())); + } + + AccountGameplayAdmissionCurrentSources.Current read( + AccountGameplayAdmissionCurrentSources.Observed observed) { + return caller.inCurrentSources(sources -> + sources.readCurrentPublicProductionNew( + hosting.tenantId(), + caller.committedCandidate.identity().tokenJti(), + caller.committedCandidate, + observed)); + } + + void refresh() { + long version = + hosting.intents().findCurrentByTenant(hosting.tenantId()).orElseThrow().rowVersion(); + assertThat( + hosting + .service() + .reconcile( + UUID.randomUUID(), + hosting.creation().requestId(), + version, + hosting.providerId(), + null) + .outcome()) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED); + } + } + Fixture newFixture(AccountGameplayDelegationRedisClient redisClient) throws Exception { return newFixture(redisClient, "latest"); } @@ -1483,6 +1959,60 @@ private static int awaitBackendBlockedBy( return -1; } + private T whileWalletInstrumentIsLockedBeforeTenantGeneration( + PaidFixture paid, Callable admissionPhase) throws Exception { + Fixture caller = paid.caller(); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try (Connection blocker = caller.dataSource.getConnection()) { + blocker.setAutoCommit(false); + int blockerPid; + try (Statement statement = blocker.createStatement(); + ResultSet pid = statement.executeQuery("SELECT pg_backend_pid()")) { + assertThat(pid.next()).isTrue(); + blockerPid = pid.getInt(1); + } + try (PreparedStatement instrumentLock = + blocker.prepareStatement( + "SELECT instrument_uuid FROM payment_instrument WHERE account_uuid = ? " + + "AND instrument_uuid = ? FOR UPDATE")) { + instrumentLock.setObject(1, paid.hosting().instrument().accountUuid()); + instrumentLock.setObject(2, paid.hosting().instrument().instrumentUuid()); + try (ResultSet instrument = instrumentLock.executeQuery()) { + assertThat(instrument.next()).isTrue(); + } + } + + Future phase = executor.submit(admissionPhase); + int blockedPid = awaitBackendBlockedBy(caller.dsl, blockerPid, 3, TimeUnit.SECONDS); + assertThat(blockedPid).isPositive().isNotEqualTo(blockerPid); + assertTenantGenerationCanBeLocked(caller.dataSource, paid.hosting().tenantId()); + blocker.rollback(); + return phase.get(5, TimeUnit.SECONDS); + } finally { + executor.shutdown(); + if (!executor.awaitTermination(5, TimeUnit.SECONDS)) executor.shutdownNow(); + } + } + + private static void assertTenantGenerationCanBeLocked(DataSource dataSource, UUID tenantId) + throws SQLException { + try (Connection probe = dataSource.getConnection()) { + probe.setAutoCommit(false); + try (PreparedStatement lock = + probe.prepareStatement( + "SELECT generation FROM account_authority_generations WHERE scope_kind = 'TENANT' " + + "AND issuer_id IS NULL AND account_uuid IS NULL AND tenant_uuid = ? " + + "FOR UPDATE NOWAIT")) { + lock.setObject(1, tenantId); + try (ResultSet row = lock.executeQuery()) { + assertThat(row.next()).isTrue(); + } + } finally { + probe.rollback(); + } + } + } + private static DataSource holdOriginalCommitBeforePhysicalCommit( DataSource delegate, CountDownLatch commitReached, @@ -1766,6 +2296,25 @@ private static Candidate candidateWithAccount(Candidate candidate, UUID accountI candidate.issuerIndexPartitionCapacity()); } + private static Candidate candidateWithTenant(Candidate candidate, UUID tenantId) { + return new Candidate( + candidate.accountId(), + tenantId, + candidate.playableStateNamespaceId(), + candidate.characterId(), + candidate.playableStateScope(), + candidate.gameInstanceId(), + candidate.runtimeGameInstanceId(), + candidate.sessionId(), + candidate.regionId(), + candidate.regionEpoch(), + candidate.issuerId(), + candidate.issuerAuthGeneration(), + candidate.issuerIndexLayoutVersion(), + candidate.issuerIndexPartitionCount(), + candidate.issuerIndexPartitionCapacity()); + } + private static Target admissionTarget(Candidate candidate, UUID requestId) { UUID realmId = UUID.randomUUID(); UUID versionId = UUID.randomUUID(); @@ -2456,6 +3005,13 @@ private CommittedCandidateVerificationData createCommittedIssuanceCandidate( private AccountGameplayAdmissionCurrentSources.Current readCurrent( CommittedCandidateVerificationData expectedCandidate) { + return inCurrentSources(sources -> + sources.readCurrentPublicProductionNew( + tenantUuid, expectedCandidate.identity().tokenJti(), expectedCandidate)); + } + + private T inCurrentSources( + java.util.function.Function read) { return serializable.execute(status -> { if (!TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isCurrentTransactionReadOnly() @@ -2472,10 +3028,8 @@ private AccountGameplayAdmissionCurrentSources.Current readCurrent( try { Integer backendBefore = exactDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class); - var current = - AccountGameplayAdmissionCurrentSources.bind(exactDsl, TEST_NAMESPACE) - .readCurrentPublicProductionNew( - tenantUuid, expectedCandidate.identity().tokenJti(), expectedCandidate); + T current = + read.apply(AccountGameplayAdmissionCurrentSources.bind(exactDsl, TEST_NAMESPACE)); Integer backendAfter = exactDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class); assertThat(backendAfter).isEqualTo(backendBefore); @@ -2514,10 +3068,16 @@ private AccountGameplayAdmissionLeaseEvidence beginPendingAdmissionLease( carrier.put("leaseId", allocation.leaseId().toString()); carrier.put("leaseFence", Long.toString(allocation.leaseFence())); carrier.put("leaseKind", "NEW_BINDING"); - carrier.put("bindingScope", bindingScope()); + Map scope = new LinkedHashMap<>(bindingScope()); + scope.put("tenantId", current.snapshot().tenantId()); + carrier.put("bindingScope", scope); carrier.putAll(current.leaseSourceFields()); carrier.put("evaluatedAt", Long.toString(evaluatedAt)); - carrier.put("expiresAt", Long.toString(evaluatedAt + 14_000L)); + long expiry = evaluatedAt + 14_000L; + if (current.sourceValidUntilMs() != null) { + expiry = Math.min(expiry, current.sourceValidUntilMs()); + } + carrier.put("expiresAt", Long.toString(expiry)); var evidence = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); leases.beginPending(evidence); return evidence; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java index 8887995142..defbde11e0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java @@ -12,6 +12,8 @@ import java.nio.file.Path; import java.security.MessageDigest; import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; @@ -86,6 +88,7 @@ class AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest { @TempDir Path temporaryDirectory; private AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest fixtureHarness; private AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.Fixture sourceFixture; + private AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PaidFixture paidFixture; private AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PhysicalRedisFixture redisFixture; @@ -103,6 +106,7 @@ static void stopPostgres() { void createActualSourceFixture() throws Exception { fixtureHarness = new AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest(); fixtureHarness.temporaryDirectory = temporaryDirectory; + paidFixture = null; redisFixture = AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PhysicalRedisFixture.start(); sourceFixture = fixtureHarness.newFixture(redisFixture.client()); @@ -124,7 +128,62 @@ void loginCallerRevokedDuringFinalReadCannotActivateThePendingCredential() throw exerciseFinalConfirmation(true); } + @Test + void paidHostingSourceIsObservedOutsideSqlForIssueAndConfirmation() throws Exception { + paidFixture = fixtureHarness.newPaidFixture(redisFixture.client()); + sourceFixture = paidFixture.caller(); + exerciseFinalConfirmation(false); + } + + @Test + void paidSourceHeadChangeDuringObservationRefusesOriginalCredentialIssuance() throws Exception { + paidFixture = fixtureHarness.newPaidFixture(redisFixture.client()); + sourceFixture = paidFixture.caller(); + exerciseFinalConfirmation(false, true); + } + + @Test + void paidConfirmationWithElapsedContinuityDoesNotWriteReadback() throws Exception { + paidFixture = fixtureHarness.newPaidFixture(redisFixture.client()); + sourceFixture = paidFixture.caller(); + exerciseFinalConfirmation(false, false, true); + } + private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) throws Exception { + exerciseFinalConfirmation(revokeCallerDuringFinalRead, false); + } + + private void exerciseFinalConfirmation( + boolean revokeCallerDuringFinalRead, boolean changePaidSourceDuringObservation) + throws Exception { + exerciseFinalConfirmation( + revokeCallerDuringFinalRead, changePaidSourceDuringObservation, false); + } + + private void exerciseFinalConfirmation( + boolean revokeCallerDuringFinalRead, + boolean changePaidSourceDuringObservation, + boolean expireContinuityDuringConfirmationObservation) + throws Exception { + AtomicReference selectedOwnerClock = new AtomicReference<>(Clock.systemUTC()); + Clock ownerClock = + new Clock() { + @Override + public ZoneId getZone() { + return selectedOwnerClock.get().getZone(); + } + + @Override + public Clock withZone(ZoneId zone) { + return selectedOwnerClock.get().withZone(zone); + } + + @Override + public Instant instant() { + return selectedOwnerClock.get().instant(); + } + }; + AtomicInteger continuityAdvances = new AtomicInteger(); DSLContext dsl = DSL.using( new TransactionAwareDataSourceProxy(sourceFixture.dataSource), SQLDialect.POSTGRES); @@ -190,6 +249,26 @@ private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) thro when(readback.canonicalSessionDurationMillis()).thenReturn(SESSION_DURATION_MILLIS); when(readback.canonicalReadbackSha256()).thenReturn("f".repeat(64)); finalReadResults.add(readback); + if (expireContinuityDuringConfirmationObservation) { + selectedOwnerClock.set( + Clock.fixed( + Instant.ofEpochMilli(controlledAdmissionAtMillis + 1), ZoneId.of("UTC"))); + paidFixture + .hosting() + .transport() + .duringRead(() -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + selectedOwnerClock.set( + Clock.fixed( + Instant.ofEpochMilli( + controlledAdmissionAtMillis + SESSION_DURATION_MILLIS), + ZoneId.of("UTC"))); + continuityAdvances.incrementAndGet(); + }); + } if (revokeCallerDuringFinalRead) { // The normal revocation owner lawfully changes the genuine LOGIN identity fence // after Account began its reverse read, without changing the original NEW lineage. @@ -218,19 +297,32 @@ private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) thro } return readback; }; + var callerVerifier = + new AccountGameplayAdmissionCallerVerifier( + sourceFixture.signerFixture.trustedJwksSource(), + sourceFixture.committedIssuanceOwner, + Clock.systemUTC()); var owner = - new AccountOriginalNewBoundGameplayCredentialOwner( - sourceFixture.dataSource, - NAMESPACE, - new AccountGameplayAdmissionCallerVerifier( - sourceFixture.signerFixture.trustedJwksSource(), - sourceFixture.committedIssuanceOwner, - Clock.systemUTC()), - sourceFixture.signerFixture.signer(), - tokenRegistry, - responseCryptography, - Clock.systemUTC(), - controlledFinalReadback); + paidFixture == null + ? new AccountOriginalNewBoundGameplayCredentialOwner( + sourceFixture.dataSource, + NAMESPACE, + callerVerifier, + sourceFixture.signerFixture.signer(), + tokenRegistry, + responseCryptography, + ownerClock, + controlledFinalReadback) + : new AccountOriginalNewBoundGameplayCredentialOwner( + sourceFixture.dataSource, + NAMESPACE, + callerVerifier, + sourceFixture.signerFixture.signer(), + tokenRegistry, + responseCryptography, + ownerClock, + controlledFinalReadback, + paidFixture.hosting().admissionPaidSource()); GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(GAME_SESSION_WORKLOAD).orElseThrow(); AccountGameplayAdmissionLeaseEvidence originalLease = commitActualOriginalNewLease(dsl, serializable); @@ -244,16 +336,33 @@ private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) thro if (originalDecisionId == null) throw new IllegalStateException("Original decision is absent"); String originalEvidenceSha256 = originalLease.sha256(); + if (changePaidSourceDuringObservation) { + paidFixture.hosting().transport().duringRead(paidFixture::refresh); + assertThatThrownBy(() -> + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .call(() -> owner.issue(loginJwt, originalLease))) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); + assertThat(dsl.fetchCount(DSL.table("account_original_new_bound_gameplay_issuances"))) + .isZero(); + assertThat(finalReadCalls.get()).isZero(); + assertOriginalLeaseAndAckRemainExact(dsl, originalLease, originalEvidenceSha256); + return; + } + OriginalNewCredential first = Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) .call(() -> owner.issue(loginJwt, originalLease)); + int paidReadsBeforeCommittedRetry = paidObservationReads(); OriginalNewCredential lostReplyRetry = Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) .call(() -> owner.issue(loginJwt, originalLease)); try (first; lostReplyRetry) { + // Current source, issuance fence, and a single source for opening the committed result. + assertPaidObservationReadsSince(paidReadsBeforeCommittedRetry, 3); Genesis committed = readGenesis(dsl, serializable, originalLease); byte[] firstHandle = first.opaqueRebindHandle(); byte[] retryHandle = lostReplyRetry.opaqueRebindHandle(); @@ -323,6 +432,16 @@ private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) thro Math.addExact( Math.multiplyExact(committed.expiresAtEpochSecond(), 1_000L), REDIS_CLEANUP_MARGIN_MILLIS); + if (expireContinuityDuringConfirmationObservation) { + String before = issuancePhysicalImage(dsl); + assertFinalConfirmationUnavailable(owner, peer, loginJwt, originalLease); + assertThat(finalReadCalls.get()).isOne(); + assertThat(continuityAdvances.get()).isOne(); + assertUnconfirmed(dsl, serializable, originalLease); + assertThat(issuancePhysicalImage(dsl)).isEqualTo(before); + assertOriginalLeaseAndAckRemainExact(dsl, originalLease, originalEvidenceSha256); + return; + } if (revokeCallerDuringFinalRead) { String issuanceBefore = dsl.fetchSingle( @@ -433,7 +552,10 @@ private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) thro // ACTIVE Redis state cannot substitute for a new authenticated Game Session final read. finalReadMode.set(FinalReadMode.CHANGED); + int paidReadsBeforeChangedFinal = paidObservationReads(); assertFinalConfirmationUnavailable(owner, peer, loginJwt, originalLease); + // Refusal happens after the same single frozen-credential open, before another paid read. + assertPaidObservationReadsSince(paidReadsBeforeChangedFinal, 3); Genesis afterChangedRead = assertUnconfirmed(dsl, serializable, originalLease); assertSameActiveRegistryReadback( activeAfterLostConfirmation, @@ -449,7 +571,10 @@ private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) thro // Recovery makes a fresh read of the same controlled final result and confirms the same // frozen lineage, token, anchors, continuity deadline, and physical registry expiry. finalReadMode.set(FinalReadMode.EXACT); + int paidReadsBeforeExactFinal = paidObservationReads(); var confirmed = confirm(owner, peer, loginJwt, originalLease); + // Early source, genesis, a single frozen-credential open, and final confirmation. + assertPaidObservationReadsSince(paidReadsBeforeExactFinal, 4); assertThat(confirmed.lineageId()).isEqualTo(first.lineageId()); assertThat(confirmed.originalLeaseId()) .isEqualTo(UUID.fromString((String) originalLease.carrier().get("leaseId"))); @@ -524,83 +649,78 @@ private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) thro assertThat(finalReadCalls.get()).isEqualTo(4); } assertOriginalLeaseAndAckRemainExact(dsl, originalLease, originalEvidenceSha256); + if (paidFixture != null) { + var transport = paidFixture.hosting().transport(); + int before = transport.reads(); + var observationsAtRefresh = new AtomicInteger(); + String issuanceBefore = issuancePhysicalImage(dsl); + // Only change the paid source at the committed credential open, after the earlier + // current-source and issuance-fence reads succeeded. + transport.duringRead(() -> + transport.duringRead(() -> + transport.duringRead(() -> { + observationsAtRefresh.set(transport.reads() - before); + paidFixture.refresh(); + }))); + assertThatThrownBy(() -> + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .call(() -> owner.issue(loginJwt, originalLease))) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); + assertThat(observationsAtRefresh.get()).isEqualTo(3); + assertThat(issuancePhysicalImage(dsl)).isEqualTo(issuanceBefore); + assertOriginalLeaseAndAckRemainExact(dsl, originalLease, originalEvidenceSha256); + } } } + private int paidObservationReads() { + return paidFixture == null ? 0 : paidFixture.hosting().transport().reads(); + } + + private void assertPaidObservationReadsSince(int prior, int expectedPaid) { + assertThat(paidObservationReads() - prior).isEqualTo(paidFixture == null ? 0 : expectedPaid); + } + private AccountGameplayAdmissionLeaseEvidence commitActualOriginalNewLease( DSLContext dsl, TransactionTemplate serializable) { UUID accountId = sourceFixture.committedCandidate.identity().accountId(); - UUID tenantId = - dsl.fetchSingle( - "SELECT membership.tenant_uuid FROM account_tenant_membership membership " - + "JOIN accounts account ON account.id = membership.account_id " - + "WHERE account.account_uuid = ? AND membership.tenant_uuid IS NOT NULL", - accountId) - .get(0, UUID.class); - if (tenantId == null) - throw new IllegalStateException("Current-source fixture tenant is absent"); - - AccountGameplayAdmissionLeaseEvidence evidence = - serializable.execute(status -> { - var current = - AccountGameplayAdmissionCurrentSources.bind(dsl, NAMESPACE) - .readCurrentPublicProductionNew( - tenantId, - sourceFixture.committedCandidate.identity().tokenJti(), - sourceFixture.committedCandidate); - UUID requestId = UUID.randomUUID(); - UUID leaseId = UUID.randomUUID(); - var leaseRepository = new AccountGameplayAdmissionLeaseRepository(dsl); - var allocation = leaseRepository.allocate(accountId, requestId, leaseId); - long evaluatedAt = - dsl.fetchSingle("SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint") - .get(0, Long.class); - long maxLeaseExpiry = - Math.addExact(evaluatedAt, AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS); - long initialTokenExpiry = - Math.multiplyExact( - sourceFixture.committedCandidate.identity().expiresAtEpochSecond(), 1_000L); - Map carrier = new LinkedHashMap<>(); - carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); - carrier.put("schemaVersion", "1"); - carrier.put("mode", "PUBLIC_PRODUCTION"); - carrier.put("targetNamespace", NAMESPACE); - carrier.put("callerWorkload", GAME_SESSION_WORKLOAD); - carrier.put("requestId", allocation.requestId().toString()); - carrier.put("leaseId", allocation.leaseId().toString()); - carrier.put("leaseFence", Long.toString(allocation.leaseFence())); - carrier.put("leaseKind", "NEW_BINDING"); - carrier.put( - "bindingScope", - Map.ofEntries( - Map.entry("accountId", accountId.toString()), - Map.entry("tenantId", tenantId.toString()), - Map.entry("realmId", UUID.randomUUID().toString()), - Map.entry("worldSlug", "world"), - Map.entry("realmSlug", "realm"), - Map.entry("playableStateNamespaceId", UUID.randomUUID().toString()), - Map.entry("playableStateScope", "SHARED"), - Map.entry("gameInstanceId", UUID.randomUUID().toString()), - Map.entry("characterId", UUID.randomUUID().toString()), - Map.entry("sessionId", UUID.randomUUID().toString()), - Map.entry("bindingGeneration", "1"), - Map.entry("catalogRevision", "1"), - Map.entry("pointerVersion", "1"), - Map.entry("regionId", UUID.randomUUID().toString()), - Map.entry("regionEpoch", "1"))); - carrier.putAll(current.leaseSourceFields()); - carrier.put("evaluatedAt", Long.toString(evaluatedAt)); - carrier.put("expiresAt", Long.toString(Math.min(maxLeaseExpiry, initialTokenExpiry))); - var originalLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); - leaseRepository.beginPending(originalLease); - return originalLease; - }); + AccountGameplayAdmissionLeaseEvidence evidence; + if (paidFixture == null) { + UUID tenantId = + dsl.fetchSingle( + "SELECT membership.tenant_uuid FROM account_tenant_membership membership " + + "JOIN accounts account ON account.id = membership.account_id " + + "WHERE account.account_uuid = ? AND membership.tenant_uuid IS NOT NULL", + accountId) + .get(0, UUID.class); + if (tenantId == null) + throw new IllegalStateException("Current-source fixture tenant is absent"); + + evidence = + serializable.execute(status -> { + var current = + AccountGameplayAdmissionCurrentSources.bind(dsl, NAMESPACE) + .readCurrentPublicProductionNew( + tenantId, + sourceFixture.committedCandidate.identity().tokenJti(), + sourceFixture.committedCandidate); + return beginPendingLease(dsl, accountId, tenantId, current); + }); + } else { + var observed = paidFixture.prepare().observeOutsideSql(); + var current = paidFixture.read(observed); + UUID tenantId = paidFixture.hosting().tenantId(); + evidence = + serializable.execute(status -> beginPendingLease(dsl, accountId, tenantId, current)); + } UUID decisionId = UUID.randomUUID(); + var paidObservation = paidFixture == null ? null : paidFixture.prepare().observeOutsideSql(); var acknowledgement = new AccountGameplayAdmissionOriginalCommitExecutor(sourceFixture.dataSource) .executeWithCurrentSources( - evidence, decisionId, NAMESPACE, sourceFixture.committedCandidate); + evidence, decisionId, NAMESPACE, sourceFixture.committedCandidate, paidObservation); var receipt = new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(sourceFixture.dataSource) .confirm(acknowledgement); @@ -609,6 +729,70 @@ private AccountGameplayAdmissionLeaseEvidence commitActualOriginalNewLease( return evidence; } + private AccountGameplayAdmissionLeaseEvidence beginPendingLease( + DSLContext dsl, + UUID accountId, + UUID tenantId, + AccountGameplayAdmissionCurrentSources.Current current) { + UUID requestId = UUID.randomUUID(); + UUID leaseId = UUID.randomUUID(); + var leaseRepository = new AccountGameplayAdmissionLeaseRepository(dsl); + var allocation = leaseRepository.allocate(accountId, requestId, leaseId); + long evaluatedAt = + dsl.fetchSingle("SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint") + .get(0, Long.class); + long maxLeaseExpiry = + Math.addExact(evaluatedAt, AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS); + long initialTokenExpiry = + Math.multiplyExact( + sourceFixture.committedCandidate.identity().expiresAtEpochSecond(), 1_000L); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("targetNamespace", NAMESPACE); + carrier.put("callerWorkload", GAME_SESSION_WORKLOAD); + carrier.put("requestId", allocation.requestId().toString()); + carrier.put("leaseId", allocation.leaseId().toString()); + carrier.put("leaseFence", Long.toString(allocation.leaseFence())); + carrier.put("leaseKind", "NEW_BINDING"); + carrier.put( + "bindingScope", + Map.ofEntries( + Map.entry("accountId", accountId.toString()), + Map.entry("tenantId", tenantId.toString()), + Map.entry("realmId", UUID.randomUUID().toString()), + Map.entry("worldSlug", "world"), + Map.entry("realmSlug", "realm"), + Map.entry("playableStateNamespaceId", UUID.randomUUID().toString()), + Map.entry("playableStateScope", "SHARED"), + Map.entry("gameInstanceId", UUID.randomUUID().toString()), + Map.entry("characterId", UUID.randomUUID().toString()), + Map.entry("sessionId", UUID.randomUUID().toString()), + Map.entry("bindingGeneration", "1"), + Map.entry("catalogRevision", "1"), + Map.entry("pointerVersion", "1"), + Map.entry("regionId", UUID.randomUUID().toString()), + Map.entry("regionEpoch", "1"))); + carrier.putAll(current.leaseSourceFields()); + carrier.put("evaluatedAt", Long.toString(evaluatedAt)); + long expiry = Math.min(maxLeaseExpiry, initialTokenExpiry); + if (current.sourceValidUntilMs() != null) { + expiry = Math.min(expiry, current.sourceValidUntilMs()); + } + carrier.put("expiresAt", Long.toString(expiry)); + var originalLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + leaseRepository.beginPending(originalLease); + return originalLease; + } + + private static String issuancePhysicalImage(DSLContext dsl) { + return dsl.fetchSingle( + "SELECT xmin::text || ':' || to_jsonb(issuance)::text" + + " FROM account_original_new_bound_gameplay_issuances issuance") + .get(0, String.class); + } + private static Genesis readGenesis( DSLContext dsl, TransactionTemplate transaction, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java index dc4be776a3..cb95a7b7d7 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java @@ -51,6 +51,7 @@ import net.firedevops.firemud.accountservice.repository.AccountBillingCustomerRecord; import net.firedevops.firemud.accountservice.repository.AccountBillingCustomerRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionPaidSource; import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePayment; import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePaymentRepository; import net.firedevops.firemud.accountservice.repository.AccountHostingPlanCatalog; @@ -314,6 +315,8 @@ private static Fixture createInternal( service, lifecycleRepository, observer, + new AccountGameplayAdmissionPaidSource( + catalog, clock, limits, policy, observer, namespace, false), source); fixture.providerStatus("active"); return fixture; @@ -1002,6 +1005,7 @@ public static final class Fixture { private final AccountHostingSubscriptionLifecycleService service; private final AccountHostingSubscriptionLifecycleRepository lifecycleRepository; private final StripeHostingSubscriptionObserver observer; + private final AccountGameplayAdmissionPaidSource admissionPaidSource; private final DataSource source; private FirstInvoiceCheckout checkout; private Path checkoutDirectory; @@ -1023,6 +1027,7 @@ private Fixture( AccountHostingSubscriptionLifecycleService service, AccountHostingSubscriptionLifecycleRepository lifecycleRepository, StripeHostingSubscriptionObserver observer, + AccountGameplayAdmissionPaidSource admissionPaidSource, DataSource source) { this.jdbc = jdbc; this.dsl = dsl; @@ -1040,6 +1045,7 @@ private Fixture( this.service = service; this.lifecycleRepository = lifecycleRepository; this.observer = observer; + this.admissionPaidSource = admissionPaidSource; this.source = source; } @@ -1120,6 +1126,10 @@ public StripeHostingSubscriptionObserver observer() { return observer; } + public AccountGameplayAdmissionPaidSource admissionPaidSource() { + return admissionPaidSource; + } + /** Uses a JUnit-owned directory for both successful and partially constructed checkouts. */ public Fixture withCheckoutDirectory(Path directory) { Objects.requireNonNull(directory, "test-owned checkout directory required"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java index 247d924fe4..4097b4b6f1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java @@ -11,6 +11,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.time.Duration; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; @@ -43,7 +44,9 @@ import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import org.flywaydb.core.Flyway; +import org.jooq.ExecuteListener; import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -89,6 +92,47 @@ void dropOwnedSchemas() { schemas.clear(); } + @Test + void canonicalJoinLocksAccountPairInSharedOrderAndDeduplicatesSelfPayer() { + Context c = context(false); + UUID payer = c.hosting.accountUuid(); + UUID caller = c.scope.accountId(); + assertThat(caller).isNotEqualTo(payer); + var captured = new ArrayList(); + var configuration = + c.hosting + .dsl() + .configuration() + .derive( + new DefaultExecuteListenerProvider( + ExecuteListener.onExecuteStart(context -> { + String sql = context.sql(); + var query = context.query(); + if (sql != null + && query != null + && sql.startsWith( + "SELECT account_uuid FROM accounts WHERE account_uuid = ") + && sql.endsWith(" FOR UPDATE")) { + captured.add((UUID) query.getBindValues().getFirst()); + } + }))); + var repository = new AccountRepository(configuration.dsl()); + + c.hosting + .transaction() + .executeWithoutResult( + status -> repository.lockCanonicalJoinAccounts(c.hosting.tenantId(), caller)); + assertThat(captured) + .containsExactlyElementsOf(List.of(caller, payer).stream().sorted().toList()); + + captured.clear(); + c.hosting + .transaction() + .executeWithoutResult( + status -> repository.lockCanonicalJoinAccounts(c.hosting.tenantId(), payer)); + assertThat(captured).containsExactly(payer); + } + @Test void paidJoinCommitsOnePlayerEventAuditAndReceiptThenExactlyReplaysWithoutProviderIo() { Context c = context(false); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwnerTest.java index 34767cf7bc..222eb5fcb2 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwnerTest.java @@ -36,6 +36,22 @@ void clearContext() { TransactionSynchronizationManager.clear(); } + @Test + void explicitPaidCompositionDoesNotBypassTheAuthenticatedWorkloadBoundary() { + var paidSource = mock(AccountGameplayAdmissionPaidSource.class); + var paidOwner = + new AccountGameplayAdmissionLeaseOwner( + callerVerifier, decisionClient, NAMESPACE, dataSource, paidSource); + withPeer( + null, + () -> + assertStatus( + Status.Code.UNAUTHENTICATED, + () -> + paidOwner.acquire(AcquireGameplayAdmissionLeaseRequest.getDefaultInstance()))); + verifyNoInteractions(callerVerifier, decisionClient, dataSource, paidSource); + } + @Test void everyPurposeRejectsMissingPeerBeforeParsingOrOwnerAccess() { withPeer( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 42eff5f790..2412aca481 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -981,6 +981,25 @@ void canonicalCommittedReplayPreservesReceiptWhenCurrentGameplayIsUnavailable(St assertEquals(9L, f.currentMembership.getMembershipVersion()); assertEquals(4L, f.currentMembership.getMembershipAuthorityGeneration()); + if ("paid".equals(sourceKind)) { + var order = + org.mockito.Mockito.inOrder(accountRepository, accountJoinOperationRepository, f.hosting); + order.verify(accountRepository).findByAccountUuidForUpdate(f.scope.accountId()); + order + .verify(accountJoinOperationRepository) + .insertCanonicalIntent(f.requestId, f.scope, f.binding); + order + .verify(accountRepository) + .lockCanonicalJoinAccounts(f.scope.tenantId(), f.scope.accountId()); + order.verify(accountRepository).findByAccountUuidForUpdate(f.scope.accountId()); + order.verify(f.hosting).prepareCurrentRead(f.scope.tenantId()); + order + .verify(accountRepository) + .lockCanonicalJoinAccounts(f.scope.tenantId(), f.scope.accountId()); + order.verify(accountRepository).findByAccountUuidForUpdate(f.scope.accountId()); + order.verify(f.hosting).readCurrent(paidFence, null); + } + org.mockito.Mockito.verify(f.terminal) .commitCanonicalJoin( f.scope, From 7e7c7e687918ee6e47596e56e97a92e7993cb4b0 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 25 Nov 2026 11:09:19 +1300 Subject: [PATCH 02/14] Address paid admission source and regression review findings --- .../account-service/api-contracts.md | 2 +- ...ccountGameplayAdmissionCurrentSources.java | 1 + .../AccountGameplayAdmissionPaidSource.java | 6 +- .../service/impl/AccountServiceImpl.java | 682 ++++++++++-------- ...CurrentSourcesPostgresIntegrationTest.java | 65 +- ...nicalFirstJoinPostgresIntegrationTest.java | 306 +++++--- .../service/impl/AccountServiceImplTest.java | 463 +++++++----- 7 files changed, 927 insertions(+), 598 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 6277453d81..bcea603a37 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -306,7 +306,7 @@ The shared codec preserves the existing 64 KiB lease and 15-second lifetime boun The never-admitted abort uses separate negative-purpose messages and the reverse `GetOriginalNewNeverAdmittedDecision` Game Session RPC. Account independently reads Game Session’s qualified exact-original closure before retaining a negative resolution; no provisional or committed decision is synthesized. The [interrupted original NEW contract](../../system-architecture-session-behavior.md#canonical-public-production-new-admission) owns irreversible selection, continuous qualification and cleanup requirements. The ordinary positive decision readers reject this purpose. The reverse negative read returns bounded `FAILED_PRECONDITION` for definitive retained-source or selector conflicts, `UNAVAILABLE` for missing or withdrawn closure qualification and transient SQL/Redis outages, and `INTERNAL` for unexpected or response-encoding failures. Caller and malformed-request refusals remain `PERMISSION_DENIED` and `INVALID_ARGUMENT`. These manual receivers remain unregistered. -The local lease owner accepts explicit `AccountGameplayAdmissionPaidSource` composition for paid NEW sources; its existing DEMO-only constructor refuses paid tenants. This adds no wire field, caller source selector or registered method. Source and proof limits are recorded in [canonical NEW admission components](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). +The local lease owner accepts explicit `AccountGameplayAdmissionPaidSource` composition for paid NEW sources. Its existing DEMO-only constructor cannot acquire or first-finalize a paid lease. It can replay an exact committed paid finalization after validating the current caller and matching the retained acknowledgement receipt, without querying the paid source. This adds no wire field, caller source selector or registered method. Source and proof limits are recorded in [canonical NEW admission components](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). #### Unknown-decision abort resolution diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java index 9bdd449bae..835e97c749 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java @@ -231,6 +231,7 @@ Current readCurrentPublicProductionNew( } requireSupportedPublicTenantTuple( caller.snapshot(), targetTenantId, event, receipt.tenantBillingSequence()); + observed.paidSource.requireReceiptStillCurrent(receipt); sourceValidUntilMs = receipt.validUntil().toEpochMilli(); } else { if (paidReceipt != null) throw unavailable(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionPaidSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionPaidSource.java index 695e72b66d..ed68100e1d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionPaidSource.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionPaidSource.java @@ -112,6 +112,11 @@ AccountHostingSubscriptionCurrentReceipt readCurrent( throw new IllegalStateException("Original paid NEW source observation required"); } var receipt = reader(exactDsl).readCurrent(observation.preparation.fence, observation.result); + requireReceiptStillCurrent(receipt); + return receipt; + } + + void requireReceiptStillCurrent(AccountHostingSubscriptionCurrentReceipt receipt) { Instant now = clock.instant(); if (receipt.evaluatedAt() == null || receipt.validUntil() == null @@ -119,7 +124,6 @@ AccountHostingSubscriptionCurrentReceipt readCurrent( || !now.isBefore(receipt.validUntil())) { throw new IllegalStateException("Current paid NEW source has expired"); } - return receipt; } private AccountHostingSubscriptionLifecycleRepository reader(DSLContext exactDsl) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 84d20a5a5b..2d51092a76 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -595,36 +595,38 @@ private CanonicalJoinPreparation prepareCanonicalJoin( String requestId, String callerBinding) { // Retain the exact policy-independent intent before any fallible source/provider work. - joinTransactionTemplate.executeWithoutResult(status -> { - lockCanonicalScopeAccount(scope); - accountJoinOperationRepository.insertCanonicalIntent(requestId, scope, callerBinding); - }); - return Objects.requireNonNull( - joinTransactionTemplate.execute(status -> { - // Lock the caller and distinct payer before source selection or a hosting read. - accountRepository.lockCanonicalJoinAccounts(scope.tenantId(), scope.accountId()); + joinTransactionTemplate.executeWithoutResult( + status -> { lockCanonicalScopeAccount(scope); - CanonicalJoinOperationEvidence operation = - accountJoinOperationRepository - .findCanonicalEvidenceForUpdateByRequestId(requestId) - .orElseThrow(); - if ("FAILED".equals(operation.status())) { - return new CanonicalJoinPreparation(operation, null, null, null); - } - SourceSelection source = - consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); - return switch (source.kind()) { - case PAID_HOSTING -> - new CanonicalJoinPreparation( - operation, - source, - null, - consumers.hosting().prepareCurrentRead(scope.tenantId())); - case NON_PAID_DEMO -> - new CanonicalJoinPreparation( - operation, source, consumers.demos().readCurrent(scope.tenantId()), null); - }; - })); + accountJoinOperationRepository.insertCanonicalIntent(requestId, scope, callerBinding); + }); + return Objects.requireNonNull( + joinTransactionTemplate.execute( + status -> { + // Lock the caller and distinct payer before source selection or a hosting read. + accountRepository.lockCanonicalJoinAccounts(scope.tenantId(), scope.accountId()); + lockCanonicalScopeAccount(scope); + CanonicalJoinOperationEvidence operation = + accountJoinOperationRepository + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow(); + if ("FAILED".equals(operation.status())) { + return new CanonicalJoinPreparation(operation, null, null, null); + } + SourceSelection source = + consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); + return switch (source.kind()) { + case PAID_HOSTING -> + new CanonicalJoinPreparation( + operation, + source, + null, + consumers.hosting().prepareCurrentRead(scope.tenantId())); + case NON_PAID_DEMO -> + new CanonicalJoinPreparation( + operation, source, consumers.demos().readCurrent(scope.tenantId()), null); + }; + })); } private CanonicalJoinResult commitCanonicalJoin( @@ -635,101 +637,105 @@ private CanonicalJoinResult commitCanonicalJoin( CanonicalJoinPreparation prepared, StripeHostingSubscriptionObserver.Result observation) { return Objects.requireNonNull( - joinTransactionTemplate.execute(status -> { - // The provider observation was outside SQL; reacquire the same Account lock order. - accountRepository.lockCanonicalJoinAccounts(scope.tenantId(), scope.accountId()); - lockCanonicalScopeAccount(scope); - requireCanonicalScopeFresh(consumers, scope); - CanonicalJoinOperationEvidence lockedOperation = - accountJoinOperationRepository - .findCanonicalEvidenceForUpdateByRequestId(requestId) - .orElseThrow(); - if ("FAILED".equals(lockedOperation.status())) { - // Preparation precedes provider/target reads. Another exact attempt may have - // finished meanwhile, including before any policy evidence could be bound. - var retained = + joinTransactionTemplate.execute( + status -> { + // The provider observation was outside SQL; reacquire the same Account lock order. + accountRepository.lockCanonicalJoinAccounts(scope.tenantId(), scope.accountId()); + lockCanonicalScopeAccount(scope); + requireCanonicalScopeFresh(consumers, scope); + CanonicalJoinOperationEvidence lockedOperation = + accountJoinOperationRepository + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow(); + if ("FAILED".equals(lockedOperation.status())) { + // Preparation precedes provider/target reads. Another exact attempt may have + // finished meanwhile, including before any policy evidence could be bound. + var retained = + accountJoinOperationRepository.finishCanonicalFailure( + requestId, scope, callerBinding, lockedOperation.outcome()); + return new CanonicalJoinResult(retained.outcome(), null, false, true); + } + SourceSelection current = + consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); + if (current.kind() != prepared.source().kind() + || !prepared.source().matches(current.checkpoint())) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Tenant source changed"); + } + final boolean gameplayAvailable; + final boolean allowPublicJoin; + final long entitlementVersion; + if (prepared.fence() != null) { + AccountHostingSubscriptionCurrentReceipt receipt = + consumers.hosting().readCurrent(prepared.fence(), observation); + gameplayAvailable = receipt.gameplayAvailable(); + allowPublicJoin = receipt.allowPublicJoin(); + entitlementVersion = receipt.entitlementVersion(); + } else { + DemoTenantEntitlementSnapshot demo = consumers.demos().revalidate(prepared.demo()); + gameplayAvailable = demo.gameplayAvailable(); + allowPublicJoin = demo.allowPublicJoin(); + entitlementVersion = demo.entitlementVersion(); + } + CanonicalJoinOperationEvidence policyBoundOperation = + accountJoinOperationRepository.bindCanonicalPolicyEvidence( + requestId, scope, callerBinding, allowPublicJoin, entitlementVersion); + Optional member = + accountTenantMembershipRepository.findFreshMembershipForUpdate( + scope.accountId(), scope.tenantId()); + boolean active = + member.filter(value -> "ACTIVE".equals(value.getLifecycleState())).isPresent(); + if ("PENDING".equals(policyBoundOperation.status()) + && (!gameplayAvailable || (!active && !allowPublicJoin))) { + String outcome = + gameplayAvailable + ? "PUBLIC_PRODUCTION_ADMISSION_DENIED" + : "TENANT_BILLING_BLOCKED"; accountJoinOperationRepository.finishCanonicalFailure( - requestId, scope, callerBinding, lockedOperation.outcome()); - return new CanonicalJoinResult(retained.outcome(), null, false, true); - } - SourceSelection current = - consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); - if (current.kind() != prepared.source().kind() - || !prepared.source().matches(current.checkpoint())) { - throw new AuthenticationException("ENTITLEMENT_UNAVAILABLE", "Tenant source changed"); - } - final boolean gameplayAvailable; - final boolean allowPublicJoin; - final long entitlementVersion; - if (prepared.fence() != null) { - AccountHostingSubscriptionCurrentReceipt receipt = - consumers.hosting().readCurrent(prepared.fence(), observation); - gameplayAvailable = receipt.gameplayAvailable(); - allowPublicJoin = receipt.allowPublicJoin(); - entitlementVersion = receipt.entitlementVersion(); - } else { - DemoTenantEntitlementSnapshot demo = consumers.demos().revalidate(prepared.demo()); - gameplayAvailable = demo.gameplayAvailable(); - allowPublicJoin = demo.allowPublicJoin(); - entitlementVersion = demo.entitlementVersion(); - } - CanonicalJoinOperationEvidence policyBoundOperation = - accountJoinOperationRepository.bindCanonicalPolicyEvidence( - requestId, scope, callerBinding, allowPublicJoin, entitlementVersion); - Optional member = - accountTenantMembershipRepository.findFreshMembershipForUpdate( - scope.accountId(), scope.tenantId()); - boolean active = - member.filter(value -> "ACTIVE".equals(value.getLifecycleState())).isPresent(); - if ("PENDING".equals(policyBoundOperation.status()) - && (!gameplayAvailable || (!active && !allowPublicJoin))) { - String outcome = - gameplayAvailable ? "PUBLIC_PRODUCTION_ADMISSION_DENIED" : "TENANT_BILLING_BLOCKED"; - accountJoinOperationRepository.finishCanonicalFailure( - requestId, scope, callerBinding, outcome); - return new CanonicalJoinResult(outcome, null, false, false); - } - var committed = - consumers - .firstJoin() - .commitCanonicalJoin( - scope, - requestId, - callerBinding, - prepared.fence() == null ? null : consumers.hosting(), - prepared.fence(), - observation); - requireCanonicalScopeFresh(consumers, scope); - Optional currentMembership = - accountTenantMembershipRepository.findFreshMembershipForUpdate( - scope.accountId(), scope.tenantId()); - if ("COMMITTED".equals(policyBoundOperation.status())) { - // A committed exact retry returns its original operation proof after the current - // policy binding above. Membership may have changed since that proof was retained; - // expose only the current admission flag, never use the old proof as admission. - return new CanonicalJoinResult( - committed.outcome(), - committed.terminalProof(), - gameplayAvailable - && currentMembership - .map(AccountTenantMembership::isGameplayAdmissionAllowed) - .orElse(false), - true); - } - AccountTenantMembership committedMembership = currentMembership.orElseThrow(); - if (committedMembership.getMembershipVersion() - != committed.terminalProof().membershipVersion() - || committedMembership.getMembershipAuthorityGeneration() - != committed.terminalProof().membershipAuthorityGeneration()) { - throw new IllegalStateException( - "Canonical JOIN result differs from current membership"); - } - return new CanonicalJoinResult( - committed.outcome(), - committed.terminalProof(), - committedMembership.isGameplayAdmissionAllowed(), - false); - })); + requestId, scope, callerBinding, outcome); + return new CanonicalJoinResult(outcome, null, false, false); + } + var committed = + consumers + .firstJoin() + .commitCanonicalJoin( + scope, + requestId, + callerBinding, + prepared.fence() == null ? null : consumers.hosting(), + prepared.fence(), + observation); + requireCanonicalScopeFresh(consumers, scope); + Optional currentMembership = + accountTenantMembershipRepository.findFreshMembershipForUpdate( + scope.accountId(), scope.tenantId()); + if ("COMMITTED".equals(policyBoundOperation.status())) { + // A committed exact retry returns its original operation proof after the current + // policy binding above. Membership may have changed since that proof was retained; + // expose only the current admission flag, never use the old proof as admission. + return new CanonicalJoinResult( + committed.outcome(), + committed.terminalProof(), + gameplayAvailable + && currentMembership + .map(AccountTenantMembership::isGameplayAdmissionAllowed) + .orElse(false), + true); + } + AccountTenantMembership committedMembership = currentMembership.orElseThrow(); + if (committedMembership.getMembershipVersion() + != committed.terminalProof().membershipVersion() + || committedMembership.getMembershipAuthorityGeneration() + != committed.terminalProof().membershipAuthorityGeneration()) { + throw new IllegalStateException( + "Canonical JOIN result differs from current membership"); + } + return new CanonicalJoinResult( + committed.outcome(), + committed.terminalProof(), + committedMembership.isGameplayAdmissionAllowed(), + false); + })); } private void requireCanonicalScopeFresh( @@ -772,28 +778,32 @@ public void setAccountBootstrapRosterReadClient(AccountBootstrapRosterReadClient private BootstrapCharacterAuthority prepareBootstrapCharacterAuthority( CanonicalScopeConsumers consumers, CanonicalJoinScopeV2 scope) { return Objects.requireNonNull( - joinTransactionTemplate.execute(status -> { - lockCanonicalScopeAccount(scope); - requireCanonicalScopeFresh(consumers, scope); - var membership = readBootstrapCharacterMembership(scope); - try { - SourceSelection source = - consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); - return new BootstrapCharacterAuthority( - source, - membership, - source.kind() == AccountTenantAuthorityEventRepository.SourceKind.NON_PAID_DEMO - ? consumers.demos().readCurrent(scope.tenantId()) - : null, - source.kind() == AccountTenantAuthorityEventRepository.SourceKind.PAID_HOSTING - ? consumers.hosting().prepareCurrentRead(scope.tenantId()) - : null, - consumers.clock().instant()); - } catch (RuntimeException failure) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", "Bootstrap entitlement source is unavailable", failure); - } - })); + joinTransactionTemplate.execute( + status -> { + accountRepository.lockCanonicalJoinAccounts(scope.tenantId(), scope.accountId()); + lockCanonicalScopeAccount(scope); + requireCanonicalScopeFresh(consumers, scope); + var membership = readBootstrapCharacterMembership(scope); + try { + SourceSelection source = + consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); + return new BootstrapCharacterAuthority( + source, + membership, + source.kind() == AccountTenantAuthorityEventRepository.SourceKind.NON_PAID_DEMO + ? consumers.demos().readCurrent(scope.tenantId()) + : null, + source.kind() == AccountTenantAuthorityEventRepository.SourceKind.PAID_HOSTING + ? consumers.hosting().prepareCurrentRead(scope.tenantId()) + : null, + consumers.clock().instant()); + } catch (RuntimeException failure) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Bootstrap entitlement source is unavailable", + failure); + } + })); } private Optional @@ -801,13 +811,14 @@ private BootstrapCharacterAuthority prepareBootstrapCharacterAuthority( try { return accountTenantMembershipRepository .findFreshMembershipForUpdate(scope.accountId(), scope.tenantId()) - .map(member -> - new AccountCanonicalPublicRealmScopeOwner.ExistingMembership( - member.getId(), - member.getLifecycleState(), - member.isGameplayAdmissionAllowed(), - member.getMembershipVersion(), - member.getMembershipAuthorityGeneration())); + .map( + member -> + new AccountCanonicalPublicRealmScopeOwner.ExistingMembership( + member.getId(), + member.getLifecycleState(), + member.isGameplayAdmissionAllowed(), + member.getMembershipVersion(), + member.getMembershipAuthorityGeneration())); } catch (RuntimeException failure) { throw new AuthenticationException( "AUTH_UNAVAILABLE", "Bootstrap membership source is unavailable", failure); @@ -819,58 +830,62 @@ private void requireBootstrapCharacterAuthority( CanonicalJoinScopeV2 scope, BootstrapCharacterAuthority prepared, StripeHostingSubscriptionObserver.Result observation) { - joinTransactionTemplate.executeWithoutResult(status -> { - lockCanonicalScopeAccount(scope); - requireCanonicalScopeFresh(consumers, scope); - var membership = readBootstrapCharacterMembership(scope); - if (!prepared.membership().equals(membership)) { - throw new AuthenticationException( - "AUTH_UNAVAILABLE", "Bootstrap membership changed during discovery"); - } - final boolean gameplayAvailable; - final boolean allowPublicJoin; - try { - SourceSelection current = - consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); - if (current.kind() != prepared.source().kind() - || !prepared.source().matches(current.checkpoint())) { - throw new IllegalStateException("Bootstrap entitlement source changed"); - } - if (prepared.fence() != null) { - var receipt = consumers.hosting().readCurrent(prepared.fence(), observation); - gameplayAvailable = receipt.gameplayAvailable(); - allowPublicJoin = receipt.allowPublicJoin(); - } else { - Instant currentTime = consumers.clock().instant(); - if (currentTime.isBefore(prepared.observedAt()) - || !currentTime.isBefore(prepared.observedAt().plusSeconds(15))) { - throw new IllegalStateException("Original bootstrap entitlement observation expired"); + joinTransactionTemplate.executeWithoutResult( + status -> { + accountRepository.lockCanonicalJoinAccounts(scope.tenantId(), scope.accountId()); + lockCanonicalScopeAccount(scope); + requireCanonicalScopeFresh(consumers, scope); + var membership = readBootstrapCharacterMembership(scope); + if (!prepared.membership().equals(membership)) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Bootstrap membership changed during discovery"); } - var demo = consumers.demos().revalidate(prepared.demo()); - gameplayAvailable = demo.gameplayAvailable(); - allowPublicJoin = demo.allowPublicJoin(); - } - } catch (RuntimeException failure) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", - "Bootstrap entitlement source is unavailable or changed", - failure); - } - if (!gameplayAvailable) { - throw new AuthenticationException( - "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); - } - if (membership.isEmpty() || "INACTIVE".equals(membership.orElseThrow().lifecycleState())) { - throw new AuthenticationException( - allowPublicJoin ? "JOIN_REQUIRED" : "PUBLIC_PRODUCTION_ADMISSION_DENIED", - allowPublicJoin ? JOIN_REQUIRED_CHARACTERS_MESSAGE : "Public enrollment is closed"); - } - if (!"ACTIVE".equals(membership.orElseThrow().lifecycleState()) - || !membership.orElseThrow().gameplayAdmissionAllowed()) { - throw new AuthenticationException( - "PUBLIC_PRODUCTION_ADMISSION_DENIED", "Membership does not allow actor discovery"); - } - }); + final boolean gameplayAvailable; + final boolean allowPublicJoin; + try { + SourceSelection current = + consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); + if (current.kind() != prepared.source().kind() + || !prepared.source().matches(current.checkpoint())) { + throw new IllegalStateException("Bootstrap entitlement source changed"); + } + if (prepared.fence() != null) { + var receipt = consumers.hosting().readCurrent(prepared.fence(), observation); + gameplayAvailable = receipt.gameplayAvailable(); + allowPublicJoin = receipt.allowPublicJoin(); + } else { + Instant currentTime = consumers.clock().instant(); + if (currentTime.isBefore(prepared.observedAt()) + || !currentTime.isBefore(prepared.observedAt().plusSeconds(15))) { + throw new IllegalStateException( + "Original bootstrap entitlement observation expired"); + } + var demo = consumers.demos().revalidate(prepared.demo()); + gameplayAvailable = demo.gameplayAvailable(); + allowPublicJoin = demo.allowPublicJoin(); + } + } catch (RuntimeException failure) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Bootstrap entitlement source is unavailable or changed", + failure); + } + if (!gameplayAvailable) { + throw new AuthenticationException( + "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); + } + if (membership.isEmpty() + || "INACTIVE".equals(membership.orElseThrow().lifecycleState())) { + throw new AuthenticationException( + allowPublicJoin ? "JOIN_REQUIRED" : "PUBLIC_PRODUCTION_ADMISSION_DENIED", + allowPublicJoin ? JOIN_REQUIRED_CHARACTERS_MESSAGE : "Public enrollment is closed"); + } + if (!"ACTIVE".equals(membership.orElseThrow().lifecycleState()) + || !membership.orElseThrow().gameplayAdmissionAllowed()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", "Membership does not allow actor discovery"); + } + }); } private record BootstrapCharacterAuthority( @@ -912,27 +927,28 @@ public List listBootstrapRealms( "AUTH_UNAVAILABLE", "Canonical public-realm scope source is unavailable"); } return owner.listRealmScopes(bootstrapToken, tenantSlug, worldSlug).stream() - .map(retained -> { - var target = retained.target(); - var scope = retained.scope(); - return new BootstrapRealmDto( - scope.worldSlug(), - scope.realmSlug(), - scope.realmId(), - target.realmDisplayName(), - scope.tenantId(), - scope.gameInstanceId(), - scope.pointerVersion(), - scope.catalogRevision(), - scope.playableStateNamespaceId(), - PlayableStateScope.valueOf("PLAYABLE_STATE_SCOPE_" + scope.playableStateScope()) - .name(), - scope.playableStateScope(), - target.characterCreationPolicy(), - scope.evaluatedAt(), - scope.connectScopeExpiresAt(), - scope.connectScopeId()); - }) + .map( + retained -> { + var target = retained.target(); + var scope = retained.scope(); + return new BootstrapRealmDto( + scope.worldSlug(), + scope.realmSlug(), + scope.realmId(), + target.realmDisplayName(), + scope.tenantId(), + scope.gameInstanceId(), + scope.pointerVersion(), + scope.catalogRevision(), + scope.playableStateNamespaceId(), + PlayableStateScope.valueOf("PLAYABLE_STATE_SCOPE_" + scope.playableStateScope()) + .name(), + scope.playableStateScope(), + target.characterCreationPolicy(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + scope.connectScopeId()); + }) .toList(); } @@ -995,13 +1011,14 @@ public List listBootstrapCharacters( .sorted( Comparator.comparing(AccountBootstrapRosterReadClient.Actor::displayName) .thenComparing(actor -> actor.characterId().toString())) - .map(actor -> - new BootstrapCharacterDto( - actor.characterId().toString(), - actor.displayName(), - actor.level(), - scope.playableStateScope(), - published.currentTarget().characterCreationPolicy())) + .map( + actor -> + new BootstrapCharacterDto( + actor.characterId().toString(), + actor.displayName(), + actor.level(), + scope.playableStateScope(), + published.currentTarget().characterCreationPolicy())) .toList(); } @@ -1114,26 +1131,30 @@ private void recordCanonicalJoinFailure( // reader rejects the same expired scope without rewriting its retained intent; preserve // that behavior when time crosses the boundary during provider I/O or the commit gate. if ("CONNECT_SCOPE_INVALID".equals(failureCode)) return; - joinTransactionTemplate.executeWithoutResult(status -> { - lockCanonicalScopeAccount(scope); - Optional found = - accountJoinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId); - if (found.isEmpty() || !"PENDING".equals(found.orElseThrow().status())) return; - if ("CONNECT_SCOPE_MISMATCH".equals(failureCode)) { - accountJoinOperationRepository.finishCanonicalFailure( - requestId, scope, callerBinding, failureCode); - } else { - String retryCode = - List.of("ADMISSION_POINTER_UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE", "AUTH_UNAVAILABLE") - .contains(failureCode) - ? failureCode - : "AUTH_UNAVAILABLE"; - String authorityAvailability = - "ENTITLEMENT_UNAVAILABLE".equals(retryCode) ? "UNAVAILABLE" : "NOT_EVALUATED"; - accountJoinOperationRepository.recordCanonicalAttemptFailure( - requestId, scope, callerBinding, authorityAvailability, retryCode); - } - }); + joinTransactionTemplate.executeWithoutResult( + status -> { + lockCanonicalScopeAccount(scope); + Optional found = + accountJoinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId); + if (found.isEmpty() || !"PENDING".equals(found.orElseThrow().status())) return; + if ("CONNECT_SCOPE_MISMATCH".equals(failureCode)) { + accountJoinOperationRepository.finishCanonicalFailure( + requestId, scope, callerBinding, failureCode); + } else { + String retryCode = + List.of( + "ADMISSION_POINTER_UNAVAILABLE", + "ENTITLEMENT_UNAVAILABLE", + "AUTH_UNAVAILABLE") + .contains(failureCode) + ? failureCode + : "AUTH_UNAVAILABLE"; + String authorityAvailability = + "ENTITLEMENT_UNAVAILABLE".equals(retryCode) ? "UNAVAILABLE" : "NOT_EVALUATED"; + accountJoinOperationRepository.recordCanonicalAttemptFailure( + requestId, scope, callerBinding, authorityAvailability, retryCode); + } + }); } @Override @@ -1272,18 +1293,20 @@ public RealmAccessGrantResult getRealmAccessGrantForRuntime( return accountRealmAccessGrantRepository .findByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( accountId, tenantId, worldSlug, realmSlug) - .map(grant -> - new RealmAccessGrantResult( - accountId, - tenantId, - worldSlug, - realmSlug, - grant.isGranted(), - grant.getGrantVersion(), - evaluatedAt.toString())) - .orElseGet(() -> - new RealmAccessGrantResult( - accountId, tenantId, worldSlug, realmSlug, false, 0L, evaluatedAt.toString())); + .map( + grant -> + new RealmAccessGrantResult( + accountId, + tenantId, + worldSlug, + realmSlug, + grant.isGranted(), + grant.getGrantVersion(), + evaluatedAt.toString())) + .orElseGet( + () -> + new RealmAccessGrantResult( + accountId, tenantId, worldSlug, realmSlug, false, 0L, evaluatedAt.toString())); } @Override @@ -1296,17 +1319,18 @@ public RealmAccessGrantResult grantRealmAccess(RealmAccessGrantRequest request) accountRealmAccessGrantRepository .findByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( request.accountId(), request.tenantId(), request.worldSlug(), request.realmSlug()) - .orElseGet(() -> { - AccountRealmAccessGrant created = new AccountRealmAccessGrant(); - created.setAccount(account); - created.setTenantId(request.tenantId()); - created.setWorldSlug(request.worldSlug()); - created.setRealmSlug(request.realmSlug()); - created.setGrantVersion(0L); - created.setGranted(true); - created.setCreatedAt(now); - return created; - }); + .orElseGet( + () -> { + AccountRealmAccessGrant created = new AccountRealmAccessGrant(); + created.setAccount(account); + created.setTenantId(request.tenantId()); + created.setWorldSlug(request.worldSlug()); + created.setRealmSlug(request.realmSlug()); + created.setGrantVersion(0L); + created.setGranted(true); + created.setCreatedAt(now); + return created; + }); grant.setGrantVersion(grant.getGrantVersion() + 1L); grant.setGranted(true); grant.setGrantedBy(request.grantedBy()); @@ -1572,13 +1596,14 @@ public CredentialVerification verifyGameplayPrimaryCredential( } authentication .emailLoginChallenge() - .ifPresent(challenge -> { - if (challenge.getId() == null - || challenge.getId() <= 0L - || !lockedAccount.getId().equals(challenge.getAccountId())) { - throw new IllegalStateException("Exact login challenge ownership is required"); - } - }); + .ifPresent( + challenge -> { + if (challenge.getId() == null + || challenge.getId() <= 0L + || !lockedAccount.getId().equals(challenge.getAccountId())) { + throw new IllegalStateException("Exact login challenge ownership is required"); + } + }); return new CredentialVerification( authentication.account().getAccountUuid(), authentication.emailLoginChallenge().map(AccountEmailLoginChallenge::getId).orElse(null)); @@ -1669,9 +1694,10 @@ private PrimaryAuthentication authenticateAccountIdentity( String username, String password, boolean allowEmailLoginOtp) { Optional accountOpt = findAccountForAuthentication(username); Account account = - accountOpt.orElseThrow(() -> - new AuthenticationException( - AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials")); + accountOpt.orElseThrow( + () -> + new AuthenticationException( + AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials")); return authenticateAccountIdentity(account, password, allowEmailLoginOtp); } @@ -1691,10 +1717,11 @@ private PrimaryAuthentication authenticateAccountIdentity( emailLoginChallenge = activeEmailLoginChallenge(account); } if (emailLoginChallenge - .filter(challenge -> - work == null - ? matchesEmailLoginOtp(challenge, password) - : work.verify(challenge.getCodeHash())) + .filter( + challenge -> + work == null + ? matchesEmailLoginOtp(challenge, password) + : work.verify(challenge.getCodeHash())) .isPresent()) { requireAuthenticationEligible(account); return new PrimaryAuthentication(account, emailLoginChallenge); @@ -1912,10 +1939,11 @@ public Map listPresenceVisibilityPolicies return Map.of(); } return profileRepository.findByTenantIdAndAccountIds(tenantId, accountIds).stream() - .filter(profile -> - profile.getAccount() != null - && profile.getAccount().getId() != null - && profile.getPresenceVisibilityPolicy() != null) + .filter( + profile -> + profile.getAccount() != null + && profile.getAccount().getId() != null + && profile.getPresenceVisibilityPolicy() != null) .collect( java.util.stream.Collectors.toUnmodifiableMap( profile -> profile.getAccount().getId(), @@ -1943,8 +1971,9 @@ public ProfileDto updateProfile(UpdateProfileRequest request) { profile.setBio(request.bio()); profile.setPresenceVisibilityPolicy(request.presenceVisibilityPolicy()); profile = profileRepository.save(profile); - runAfterCommit(() -> - notificationService.sendNotification(request.tenantId(), accountId, "Profile updated")); + runAfterCommit( + () -> + notificationService.sendNotification(request.tenantId(), accountId, "Profile updated")); return projectProfile(profile, request.tenantId(), accountId); } @@ -2084,12 +2113,14 @@ public void requestPasswordReset(PasswordResetRequest request) { token.setExpiresAt(java.time.LocalDateTime.now().plusHours(1)); passwordResetTokenRepository.save(token); String url = String.format(mailProperties.getResetUrl(), token.getToken()); - runAfterCommit(() -> - sendRecoveryEmailSafely(() -> - emailService.sendEmail( - account.getEmail(), - "Password Reset", - String.format(readTemplate("password-reset.txt"), url)))); + runAfterCommit( + () -> + sendRecoveryEmailSafely( + () -> + emailService.sendEmail( + account.getEmail(), + "Password Reset", + String.format(readTemplate("password-reset.txt"), url)))); } @Override @@ -2104,8 +2135,10 @@ public void completePasswordReset(CompletePasswordResetRequest request) { String tokenHash = sha256Hex(request.token()); String candidatePasswordVerifier = hashPassword(request.newPassword()); PasswordResetAttempt attempt = - passwordResetOwnerTransaction.execute(status -> - completePasswordResetInOwnerTransaction(request, tokenHash, candidatePasswordVerifier)); + passwordResetOwnerTransaction.execute( + status -> + completePasswordResetInOwnerTransaction( + request, tokenHash, candidatePasswordVerifier)); if (attempt == null) { throw new IllegalStateException("Password-reset owner transaction returned no result"); } @@ -2118,11 +2151,14 @@ public void completePasswordReset(CompletePasswordResetRequest request) { PasswordResetReceipt committed = Objects.requireNonNull(attempt.receipt(), "Committed password-reset receipt is required"); PasswordResetReceipt postCommitReadback = - passwordResetOwnerTransaction.execute(status -> - passwordResetOperationRepository - .findByTokenHash(tokenHash) - .orElseThrow(() -> - new IllegalStateException("Password-reset receipt disappeared after commit"))); + passwordResetOwnerTransaction.execute( + status -> + passwordResetOperationRepository + .findByTokenHash(tokenHash) + .orElseThrow( + () -> + new IllegalStateException( + "Password-reset receipt disappeared after commit"))); if (!committed.equals(postCommitReadback)) { throw new IllegalStateException("Password-reset committed receipt readback differs"); } @@ -2141,12 +2177,17 @@ private PasswordResetAttempt completePasswordResetInOwnerTransaction( Long accountId = resolvedReceipt .map(PasswordResetReceipt::accountId) - .orElseGet(() -> - resolvedIntentAccountId.orElseGet(() -> - resolvedToken - .map( - token -> token.getAccount() == null ? null : token.getAccount().getId()) - .orElse(null))); + .orElseGet( + () -> + resolvedIntentAccountId.orElseGet( + () -> + resolvedToken + .map( + token -> + token.getAccount() == null + ? null + : token.getAccount().getId()) + .orElse(null))); if (accountId == null || accountId <= 0L) { throw new IllegalArgumentException("Invalid token"); } @@ -2843,12 +2884,15 @@ public void sendUsernameReminder(UsernameRecoveryRequest request) { return; } Account account = accountOptional.get(); - runAfterCommit(() -> - sendRecoveryEmailSafely(() -> - emailService.sendEmail( - account.getEmail(), - "Username Reminder", - String.format(readTemplate("username-reminder.txt"), account.getUsername())))); + runAfterCommit( + () -> + sendRecoveryEmailSafely( + () -> + emailService.sendEmail( + account.getEmail(), + "Username Reminder", + String.format( + readTemplate("username-reminder.txt"), account.getUsername())))); } private void sendRecoveryEmailSafely(Runnable delivery) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index 34bf5c77a7..c7c24a4179 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -137,6 +137,7 @@ import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; +import org.jooq.ExecuteListener; import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -438,6 +439,55 @@ void paidObservationCannotRunInsideThePreparingAccountTransaction() throws Excep assertThat(paid.hosting().transport().reads()).isEqualTo(reads); } + @Test + void paidReceiptExpiringDuringFinalCallerSourceReadIsUnavailableWithoutWrites() throws Exception { + PaidFixture paid = newPaidFixture(null); + Fixture caller = paid.caller(); + var observed = paid.prepare().observeOutsideSql(); + long validUntil = paid.read(observed).sourceValidUntilMs(); + Instant pastDeadline = Instant.ofEpochMilli(validUntil).plusMillis(1); + UUID originalJti = caller.committedCandidate.identity().tokenJti(); + int providerReads = paid.hosting().transport().reads(); + var before = caller.sourceAndIssuanceImage(); + var reachedCallerRead = new AtomicBoolean(); + // This exact issuance SELECT is downstream of the paid receipt read and early clock check. + var expireDuringCallerRead = + ExecuteListener.onExecuteEnd( + ctx -> { + String sql = ctx.sql(); + var query = ctx.query(); + if (sql != null + && sql.contains( + "SELECT request_id FROM account_gameplay_delegation_issuance_operations") + && sql.contains("WHERE token_jti = ? AND status = 'COMMITTED'") + && query != null + && query.getBindValues().equals(List.of(originalJti)) + && reachedCallerRead.compareAndSet(false, true)) { + assertThat(paid.hosting().clock().instant()) + .isBefore(Instant.ofEpochMilli(validUntil)); + paid.hosting().clock().advanceToAtLeast(pastDeadline); + } + }); + + assertThatThrownBy( + () -> + caller.inCurrentSources( + sources -> + sources.readCurrentPublicProductionNew( + paid.hosting().tenantId(), + originalJti, + caller.committedCandidate, + observed), + expireDuringCallerRead)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Current paid NEW source has expired"); + assertThat(reachedCallerRead).isTrue(); + assertThat(paid.hosting().clock().instant()).isEqualTo(pastDeadline); + assertThat(paid.hosting().transport().reads()).isEqualTo(providerReads); + assertThat(caller.sourceAndIssuanceImage()).isEqualTo(before); + assertThat(caller.leaseOperationCount()).isZero(); + } + @Test void paidObservationExpiryAndContradictoryProviderFactsCannotFinalizeTheOriginalLease() throws Exception { @@ -538,6 +588,9 @@ void authenticatedPaidOwnerCapsTheLeaseFinalizesOnceAndRecoversWithoutPaidAuthor requestId, jwt, candidate, target, BigInteger.ONE); var response = new AtomicReference(); var before = caller.sourceAndIssuanceImageForAuthenticatedCommit(); + long acquisitionDatabaseMillis = + caller.inSerializableTransaction(caller::currentDatabaseMillisOnEnlistedConnection); + paid.hosting().clock().advanceToAtLeast(Instant.ofEpochMilli(acquisitionDatabaseMillis)); withPeer(peer, () -> response.set(owner.acquire(acquire))); var lease = AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireResponse( @@ -3012,6 +3065,12 @@ private AccountGameplayAdmissionCurrentSources.Current readCurrent( private T inCurrentSources( java.util.function.Function read) { + return inCurrentSources(read, null); + } + + private T inCurrentSources( + java.util.function.Function read, + ExecuteListener listener) { return serializable.execute(status -> { if (!TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isCurrentTransactionReadOnly() @@ -3024,7 +3083,11 @@ private T inCurrentSources( throw new IllegalStateException("Expected the manager-enlisted Account connection"); } Connection connection = holder.getConnection(); - DSLContext exactDsl = DSL.using(connection, SQLDialect.POSTGRES); + DSLContext boundDsl = DSL.using(connection, SQLDialect.POSTGRES); + DSLContext exactDsl = + listener == null + ? boundDsl + : DSL.using(boundDsl.configuration().deriveAppending(listener)); try { Integer backendBefore = exactDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java index 4097b4b6f1..1775430ff2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java @@ -10,14 +10,21 @@ import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.sql.SQLException; import java.time.Duration; import java.util.ArrayList; +import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.LockSupport; +import javax.sql.DataSource; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.entity.Account; @@ -45,6 +52,7 @@ import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import org.flywaydb.core.Flyway; import org.jooq.ExecuteListener; +import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.AfterAll; @@ -53,9 +61,12 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; /** * Physical Account transaction and real SDK decoding against a controlled local Stripe transport. @@ -105,17 +116,18 @@ void canonicalJoinLocksAccountPairInSharedOrderAndDeduplicatesSelfPayer() { .configuration() .derive( new DefaultExecuteListenerProvider( - ExecuteListener.onExecuteStart(context -> { - String sql = context.sql(); - var query = context.query(); - if (sql != null - && query != null - && sql.startsWith( - "SELECT account_uuid FROM accounts WHERE account_uuid = ") - && sql.endsWith(" FOR UPDATE")) { - captured.add((UUID) query.getBindValues().getFirst()); - } - }))); + ExecuteListener.onExecuteStart( + context -> { + String sql = context.sql(); + var query = context.query(); + if (sql != null + && query != null + && sql.startsWith( + "SELECT account_uuid FROM accounts WHERE account_uuid = ") + && sql.endsWith(" FOR UPDATE")) { + captured.add((UUID) query.getBindValues().getFirst()); + } + }))); var repository = new AccountRepository(configuration.dsl()); c.hosting @@ -133,6 +145,115 @@ void canonicalJoinLocksAccountPairInSharedOrderAndDeduplicatesSelfPayer() { assertThat(captured).containsExactly(payer); } + @Test + void orderedPaidHostingReadsDoNotHoldLaterCallerWhileWaitingForEarlierPayer() throws Exception { + DataSource source = migratedSource(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + var accounts = new AccountRepository(dsl); + var candidates = new ArrayList(); + transaction.executeWithoutResult( + status -> { + for (int i = 0; i < 2; i++) { + var account = new Account(); + String name = "physical-pair-" + UUID.randomUUID(); + account.setUsername(name); + account.setEmail(name + "@example.test"); + account.setPasswordHash("controlled-hash"); + candidates.add(accounts.save(account)); + } + }); + candidates.sort(Comparator.comparing(Account::getAccountUuid)); + Account earlierPayer = candidates.getFirst(); + UUID payer = earlierPayer.getAccountUuid(); + UUID caller = candidates.getLast().getAccountUuid(); + assertThat(payer.compareTo(caller)).isNegative(); + + var hosting = + CanonicalHostingSubscriptionTestFixture.create(source, earlierPayer) + .withCheckoutDirectory(invoiceCheckoutDirectory); + assertThat(hosting.completeFirstInvoice().outcome()) + .isEqualTo( + net.firedevops.firemud.accountservice.repository + .AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED); + hosting.transaction().setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + UUID tenant = hosting.tenantId(); + var lifecycle = hosting.lifecycleRepository(); + ReadFence fence = transaction.execute(status -> lifecycle.prepareCurrentRead(tenant)); + var observation = hosting.observer().observe(Objects.requireNonNull(fence).binding()); + + // The genuine paid hosting preparation and revalidation each acquire the same Account pair. + // A separate holder prevents the earlier payer lock from completing. There is no intentional + // cycle: another session must still be able to acquire the later caller immediately. + try (var workers = Executors.newSingleThreadExecutor()) { + for (boolean revalidating : List.of(false, true)) { + var waitingPid = new CompletableFuture(); + var done = + transaction.execute( + status -> { + int holderPid = + Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class); + accounts.findByAccountUuidForUpdate(payer).orElseThrow(); + var worker = + workers.submit( + () -> + transaction.executeWithoutResult( + ignored -> { + dsl.execute("SET LOCAL lock_timeout = '8s'"); + waitingPid.complete( + Objects.requireNonNull( + dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + accounts.lockCanonicalJoinAccounts(tenant, caller); + accounts.findByAccountUuidForUpdate(caller).orElseThrow(); + if (revalidating) { + assertThat( + lifecycle + .readCurrent(fence, observation) + .gameplayAvailable()) + .isTrue(); + } else { + assertThat(lifecycle.prepareCurrentRead(tenant).binding()) + .isEqualTo(fence.binding()); + } + })); + int waiter = waitingPid.orTimeout(4, TimeUnit.SECONDS).join(); + assertThat(waiter).isNotEqualTo(holderPid); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(4); + while (!Boolean.TRUE.equals( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT ? = ANY(pg_blocking_pids(?))", holderPid, waiter)) + .get(0, Boolean.class))) { + if (System.nanoTime() >= deadline) { + throw new AssertionError( + "Ordered read did not block on the earlier payer Account"); + } + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10)); + } + try (var connection = source.getConnection(); + var query = + connection.prepareStatement( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE" + + " NOWAIT")) { + query.setObject(1, caller); + try (var selected = query.executeQuery()) { + assertThat(selected.next()).isTrue(); + assertThat(selected.getObject(1, UUID.class)).isEqualTo(caller); + } + } catch (SQLException failure) { + throw new AssertionError( + "Earlier payer wait must leave caller Account unlocked", failure); + } + return worker; + }); + Objects.requireNonNull(done).get(5, TimeUnit.SECONDS); + } + } + } + @Test void paidJoinCommitsOnePlayerEventAuditAndReceiptThenExactlyReplaysWithoutProviderIo() { Context c = context(false); @@ -205,31 +326,40 @@ void expiredPaidReceiptIsUnavailableAndNeverSelectsDemo() { void finalCommitFailureRollsBackMembershipRolesPairEventAuditAndTerminalReceipt() { Context c = context(false); var original = c.operation(); - assertThatThrownBy(() -> - c.hosting - .transaction() - .execute(status -> { - TransactionSynchronizationManager.registerSynchronization( - new TransactionSynchronization() { - @Override - public void beforeCommit(boolean readOnly) { - throw new IllegalStateException( - "controlled final paid JOIN commit refusal"); - } - }); - return c.coordinator.commitPaidCanonicalFirstJoin( - c.scope, - c.requestId, - CALLER, - c.hosting.lifecycleRepository(), - c.fence, - c.observed); - })) + assertThatThrownBy( + () -> + c.hosting + .transaction() + .execute( + status -> { + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void beforeCommit(boolean readOnly) { + throw new IllegalStateException( + "controlled final paid JOIN commit refusal"); + } + }); + return c.coordinator.commitPaidCanonicalFirstJoin( + c.scope, + c.requestId, + CALLER, + c.hosting.lifecycleRepository(), + c.fence, + c.observed); + })) .hasMessageContaining("controlled final paid JOIN commit refusal"); c.assertRolledBack(original); } private Context context(boolean wrongPolicy) { + return new Context( + CanonicalHostingSubscriptionTestFixture.create(migratedSource()), + wrongPolicy, + invoiceCheckoutDirectory); + } + + private DataSource migratedSource() { String schema = PREFIX + UUID.randomUUID().toString().replace("-", ""); schemas.add(schema); var source = POSTGRES.dataSource(schema); @@ -241,10 +371,7 @@ private Context context(boolean wrongPolicy) { .locations("classpath:db/migration") .load() .migrate(); - return new Context( - CanonicalHostingSubscriptionTestFixture.create(source), - wrongPolicy, - invoiceCheckoutDirectory); + return source; } private static final class Context { @@ -343,40 +470,43 @@ private Context( now.plusSeconds(120).toString()); hosting .transaction() - .executeWithoutResult(status -> { - var source = fresh.read(hosting.tenantId()).orElseThrow(); - sources.initializeIssuerIfAbsent("firemud-account-service"); - generations.initialize( - AccountAuthorityGenerationRepository.AuthorityScope.membership( - player.getAccountUuid(), hosting.tenantId())); - scopes.insertCanonical( - player.getId(), - scope, - new VerifiedTenantProvenance( - null, - TenantProvenanceKind.FRESH_GAME_DESIGN, - source.operationId(), - source.evidenceDigest())); - operations.insertCanonicalIntent(requestId, scope, CALLER); - }); + .executeWithoutResult( + status -> { + var source = fresh.read(hosting.tenantId()).orElseThrow(); + sources.initializeIssuerIfAbsent("firemud-account-service"); + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + player.getAccountUuid(), hosting.tenantId())); + scopes.insertCanonical( + player.getId(), + scope, + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest())); + operations.insertCanonicalIntent(requestId, scope, CALLER); + }); fence = Objects.requireNonNull( hosting .transaction() - .execute(status -> - hosting.lifecycleRepository().prepareCurrentRead(hosting.tenantId()))); + .execute( + status -> + hosting.lifecycleRepository().prepareCurrentRead(hosting.tenantId()))); observed = hosting.observer().observe(fence.binding()); hosting .transaction() - .executeWithoutResult(status -> { - var receipt = hosting.lifecycleRepository().readCurrent(fence, observed); - operations.bindCanonicalPolicyEvidence( - requestId, - scope, - CALLER, - receipt.allowPublicJoin(), - receipt.entitlementVersion() + (wrongPolicy ? 1 : 0)); - }); + .executeWithoutResult( + status -> { + var receipt = hosting.lifecycleRepository().readCurrent(fence, observed); + operations.bindCanonicalPolicyEvidence( + requestId, + scope, + CALLER, + receipt.allowPublicJoin(), + receipt.entitlementVersion() + (wrongPolicy ? 1 : 0)); + }); paidAuditRows = auditRows(); assertThat(paidAuditRows).isNotEmpty(); } @@ -386,28 +516,30 @@ private AccountJoinOperationRepository.CanonicalJoinTerminalProof commit( return Objects.requireNonNull( hosting .transaction() - .execute(status -> - coordinator.commitPaidCanonicalFirstJoin( - scope, requestId, CALLER, hosting.lifecycleRepository(), fence, result))); + .execute( + status -> + coordinator.commitPaidCanonicalFirstJoin( + scope, requestId, CALLER, hosting.lifecycleRepository(), fence, result))); } private AccountJoinOperationRepository.CanonicalJoinOperationEvidence operation() { return Objects.requireNonNull( hosting .transaction() - .execute(status -> { - operations.lockAccount( - Objects.requireNonNull( - hosting - .dsl() - .fetchOne( - "SELECT id FROM accounts WHERE account_uuid = ?", - scope.accountId())) - .get(0, Long.class)); - return operations - .findCanonicalEvidenceForUpdateByRequestId(requestId) - .orElseThrow(); - })); + .execute( + status -> { + operations.lockAccount( + Objects.requireNonNull( + hosting + .dsl() + .fetchOne( + "SELECT id FROM accounts WHERE account_uuid = ?", + scope.accountId())) + .get(0, Long.class)); + return operations + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow(); + })); } private String stream() { @@ -426,8 +558,8 @@ private List> auditRows() { return hosting .dsl() .fetch( - "SELECT audit_event_id, row_to_json(audit)::text AS row_image, xmin::text AS row_xmin " - + "FROM account_audit_outbox audit ORDER BY audit_event_id") + "SELECT audit_event_id, row_to_json(audit)::text AS row_image, xmin::text AS row_xmin" + + " FROM account_audit_outbox audit ORDER BY audit_event_id") .intoMaps(); } @@ -437,8 +569,9 @@ private void assertCommittedAudit( hosting .dsl() .fetch( - "SELECT audit_event_id, row_to_json(audit)::text AS row_image, xmin::text AS row_xmin " - + "FROM account_audit_outbox audit WHERE audit_event_id <> ? ORDER BY audit_event_id", + "SELECT audit_event_id, row_to_json(audit)::text AS row_image, xmin::text AS" + + " row_xmin FROM account_audit_outbox audit WHERE audit_event_id <> ?" + + " ORDER BY audit_event_id", proof.auditEventId()) .intoMaps()) .isEqualTo(paidAuditRows); @@ -446,10 +579,11 @@ private void assertCommittedAudit( Objects.requireNonNull( hosting .transaction() - .execute(status -> - new AccountAuditOutboxRepository(hosting.dsl()) - .findCanonicalTenantEnvelopeForUpdate(proof.auditEventId()) - .orElseThrow())); + .execute( + status -> + new AccountAuditOutboxRepository(hosting.dsl()) + .findCanonicalTenantEnvelopeForUpdate(proof.auditEventId()) + .orElseThrow())); assertThat(joined.auditEventId()).isEqualTo(proof.auditEventId()); assertThat(joined.eventType()).isEqualTo("ACCOUNT_JOINED_PUBLIC_PRODUCTION"); assertThat(joined.tenantUuid()).isEqualTo(scope.tenantId()); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 2412aca481..8a249ab50d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -330,10 +330,11 @@ void bootstrapRealmsKeepsPlayerContextForTheComposedOwnersWorkloadGuard() { service.setCanonicalPublicRealmScopeOwner(owner); SessionContext.setContext("e9e3aa54-9712-4e01-8767-f23f3c662e64", List.of(), Map.of()); when(owner.listRealmScopes("bootstrap", "source-tenant", "demo")) - .thenAnswer(invocation -> { - assertTrue(SessionContext.hasAuthenticatedCallerContext()); - throw new IllegalStateException("Canonical source requires workload-only context"); - }); + .thenAnswer( + invocation -> { + assertTrue(SessionContext.hasAuthenticatedCallerContext()); + throw new IllegalStateException("Canonical source requires workload-only context"); + }); try { assertThrows( IllegalStateException.class, @@ -451,9 +452,10 @@ private enum IdentityFailure { private static java.util.stream.Stream ordinaryIssuanceIdentityFailures() { return java.util.Arrays.stream(OrdinaryIssuance.values()) - .flatMap(mode -> - java.util.Arrays.stream(IdentityFailure.values()) - .map(failure -> org.junit.jupiter.params.provider.Arguments.of(mode, failure))); + .flatMap( + mode -> + java.util.Arrays.stream(IdentityFailure.values()) + .map(failure -> org.junit.jupiter.params.provider.Arguments.of(mode, failure))); } @ParameterizedTest @@ -778,14 +780,15 @@ void createAccountPersistsOnlyGlobalIdentity() { new CreateAccountRequest("demo", " DEMO@example.com ", "password"); UUID accountUuid = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) - .thenAnswer(invocation -> { - Account saved = invocation.getArgument(0); - saved.setId(1L); - saved.setAccountUuid(accountUuid); - saved.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); - saved.setAccountUuidSourceNumericId(1L); - return saved; - }); + .thenAnswer( + invocation -> { + Account saved = invocation.getArgument(0); + saved.setId(1L); + saved.setAccountUuid(accountUuid); + saved.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + saved.setAccountUuidSourceNumericId(1L); + return saved; + }); AccountDto dto = service.createAccount(request); @@ -809,14 +812,15 @@ void createAccountPersistsOnlyGlobalIdentity() { @Test void createAccountRejectsPublicIdentityWithoutExactPersistedSourceRow() { when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) - .thenAnswer(invocation -> { - Account saved = invocation.getArgument(0); - saved.setId(1L); - saved.setAccountUuid(UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b")); - saved.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); - saved.setAccountUuidSourceNumericId(2L); - return saved; - }); + .thenAnswer( + invocation -> { + Account saved = invocation.getArgument(0); + saved.setId(1L); + saved.setAccountUuid(UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b")); + saved.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + saved.setAccountUuidSourceNumericId(2L); + return saved; + }); assertThrows( IllegalStateException.class, @@ -1247,16 +1251,18 @@ void canonicalJoinOutageKeepsTheIntentRetryableAndRecoversTheSameRequest(String when(f.demos.revalidate(f.demo)).thenThrow(unavailable).thenReturn(f.demo); case "member" -> org.mockito.Mockito.doThrow(unavailable) - .doAnswer(invocation -> - f.joined.get() ? Optional.of(f.currentMembership) : Optional.empty()) + .doAnswer( + invocation -> + f.joined.get() ? Optional.of(f.currentMembership) : Optional.empty()) .when(accountTenantMembershipRepository) .findFreshMembershipForUpdate(f.scope.accountId(), f.scope.tenantId()); case "terminal" -> org.mockito.Mockito.doThrow(unavailable) - .doAnswer(invocation -> { - f.joined.set(true); - return f.committed; - }) + .doAnswer( + invocation -> { + f.joined.set(true); + return f.committed; + }) .when(f.terminal) .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); default -> throw new AssertionError(stage); @@ -1324,8 +1330,10 @@ void canonicalJoinChangedTargetBetweenStrictReadsIsTerminalWithoutMembershipEffe org.mockito.Mockito.mock(Target.class, org.mockito.AdditionalAnswers.delegatesTo(f.target)); when(changed.activeWorldEpoch()).thenReturn(2L); var reads = new java.util.concurrent.atomic.AtomicInteger(); - org.mockito.Mockito.doAnswer(invocation -> - f.resolve(invocation.getArgument(0), reads.incrementAndGet() == 1 ? f.target : changed)) + org.mockito.Mockito.doAnswer( + invocation -> + f.resolve( + invocation.getArgument(0), reads.incrementAndGet() == 1 ? f.target : changed)) .when(f.targets) .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); assertEquals( @@ -1483,9 +1491,10 @@ void canonicalJoinExpiryAtCommitGatesDoesNotRewritePendingIntent(boolean afterCo var f = canonicalJoinFixture(); var clock = org.mockito.Mockito.mock(Clock.class); when(clock.instant()) - .thenAnswer(invocation -> - Instant.parse(f.scope.evaluatedAt()) - .plusSeconds(!afterCoordinator || f.joined.get() ? 120 : 1)); + .thenAnswer( + invocation -> + Instant.parse(f.scope.evaluatedAt()) + .plusSeconds(!afterCoordinator || f.joined.get() ? 120 : 1)); f.compose(clock); assertEquals( @@ -1522,8 +1531,9 @@ void canonicalJoinReturnsCommittedReceiptWhenScopeExpiresAfterCommit() { var committed = new AtomicBoolean(); var clock = org.mockito.Mockito.mock(Clock.class); when(clock.instant()) - .thenAnswer(invocation -> - Instant.parse(f.scope.evaluatedAt()).plusSeconds(committed.get() ? 120 : 1)); + .thenAnswer( + invocation -> + Instant.parse(f.scope.evaluatedAt()).plusSeconds(committed.get() ? 120 : 1)); f.compose(clock); org.mockito.Mockito.doAnswer( invocation -> { @@ -1685,10 +1695,11 @@ void canonicalDirectJoinUsesTheSameTerminalOwnerAndUuidTargetWithoutBootstrapSes org.mockito.Mockito.clearInvocations(sessionService); var result = canonicalGameSessionPeer() - .call(() -> - service.joinPublicProductionFromGameSession( - caller, - new JoinPublicProductionRequest(f.scope.connectScopeId(), f.requestId))); + .call( + () -> + service.joinPublicProductionFromGameSession( + caller, + new JoinPublicProductionRequest(f.scope.connectScopeId(), f.requestId))); assertTrue(result.success()); assertEquals(f.scope.tenantId(), result.tenantId()); assertFalse(result.replayed()); @@ -1716,14 +1727,15 @@ void canonicalDirectJoinRejectsWrongWorkloadBeforeReadingScope(String mismatch) } assertEquals( "AUTH_UNAVAILABLE", - peer.call(() -> - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProductionFromGameSession( - f.directCaller(f.requestId), - new JoinPublicProductionRequest( - f.scope.connectScopeId(), f.requestId)))) + peer.call( + () -> + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProductionFromGameSession( + f.directCaller(f.requestId), + new JoinPublicProductionRequest( + f.scope.connectScopeId(), f.requestId)))) .getCode()); verifyNoInteractions(f.reader, accountJoinOperationRepository, f.terminal); } @@ -1746,14 +1758,15 @@ void canonicalDirectJoinRejectsAnyCallerTargetMismatchBeforeIntent(String field) assertEquals( "CONNECT_SCOPE_MISMATCH", canonicalGameSessionPeer() - .call(() -> - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProductionFromGameSession( - caller, - new JoinPublicProductionRequest( - f.scope.connectScopeId(), f.requestId)))) + .call( + () -> + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProductionFromGameSession( + caller, + new JoinPublicProductionRequest( + f.scope.connectScopeId(), f.requestId)))) .getCode()); verifyNoInteractions(accountJoinOperationRepository, f.terminal); } @@ -1899,42 +1912,43 @@ private CanonicalJoinFixture(String requestId) { when(targets.resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any())) .thenAnswer(invocation -> resolve(invocation.getArgument(0), target)); when(targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) - .thenAnswer(invocation -> { - var strict = - invocation.getArgument( - 0, - net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence - .Request.class); - Target currentTarget = resolvedTarget; - long activeWorldEpoch = currentTarget.activeWorldEpoch(); - var published = - org.mockito.Mockito.mock( - net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence - .class); - when(published.selector()).thenReturn(strict); - when(published.currentTarget()).thenReturn(currentTarget); - var sourceEvidence = - org.mockito.Mockito.mock( - net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence - .class); - when(sourceEvidence.request()).thenReturn(strict); - var policies = - org.mockito.Mockito.mock( - net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence - .class); - when(policies.canonicalBytes()).thenReturn(policyBytes); - when(sourceEvidence.publishedPolicySetEvidence()).thenReturn(policies); - when(published.sourceEvidence()).thenReturn(sourceEvidence); - var world = - org.mockito.Mockito.mock( - net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence - .class); - when(world.lifecycleStatus()).thenReturn("ACTIVE"); - when(world.lifecycleEpoch()).thenReturn(activeWorldEpoch); - when(published.worldLifecycleEvidence()).thenReturn(world); - return published; - }); + .thenAnswer( + invocation -> { + var strict = + invocation.getArgument( + 0, + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .Request.class); + Target currentTarget = resolvedTarget; + long activeWorldEpoch = currentTarget.activeWorldEpoch(); + var published = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + .class); + when(published.selector()).thenReturn(strict); + when(published.currentTarget()).thenReturn(currentTarget); + var sourceEvidence = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .class); + when(sourceEvidence.request()).thenReturn(strict); + var policies = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.publication + .PublishedRealmEntryPolicySetEvidence.class); + when(policies.canonicalBytes()).thenReturn(policyBytes); + when(sourceEvidence.publishedPolicySetEvidence()).thenReturn(policies); + when(published.sourceEvidence()).thenReturn(sourceEvidence); + var world = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence + .class); + when(world.lifecycleStatus()).thenReturn("ACTIVE"); + when(world.lifecycleEpoch()).thenReturn(activeWorldEpoch); + when(published.worldLifecycleEvidence()).thenReturn(world); + return published; + }); when(pending.status()).thenReturn("PENDING"); when(accountJoinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId)) .thenReturn(Optional.of(pending)); @@ -1968,10 +1982,11 @@ private CanonicalJoinFixture(String requestId) { org.mockito.ArgumentMatchers.isNull(), org.mockito.ArgumentMatchers.isNull(), org.mockito.ArgumentMatchers.isNull())) - .thenAnswer(invocation -> { - joined.set(true); - return committed; - }); + .thenAnswer( + invocation -> { + joined.set(true); + return committed; + }); service.setAccountBootstrapRosterReadClient(roster); compose(Clock.fixed(now.plusSeconds(1), java.time.ZoneOffset.UTC)); } @@ -2090,9 +2105,10 @@ private DirectTextCallerContext directCaller(String id) { assertEquals(List.of(12, 37), actors.stream().map(value -> value.level()).toList()); assertTrue( actors.stream() - .allMatch(value -> - "SHARED".equals(value.stateScope()) - && "PRESEEDED_ONLY".equals(value.characterCreationPolicy()))); + .allMatch( + value -> + "SHARED".equals(value.stateScope()) + && "PRESEEDED_ONLY".equals(value.characterCreationPolicy()))); var target = org.mockito.ArgumentCaptor.forClass( net.firedevops.firemud.common.gamesession @@ -2117,6 +2133,59 @@ private DirectTextCallerContext directCaller(String id) { verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); } + @Test + void paidBootstrapCharactersLocksCanonicalAccountsBeforeEveryHostingRead() { + var f = canonicalJoinFixture(); + f.joined.set(true); + when(f.source.kind()).thenReturn(SourceKind.PAID_HOSTING); + var paidFence = + org.mockito.Mockito.mock(AccountHostingSubscriptionLifecycleRepository.ReadFence.class); + var paidReceipt = org.mockito.Mockito.mock(AccountHostingSubscriptionCurrentReceipt.class); + when(f.hosting.prepareCurrentRead(f.scope.tenantId())).thenReturn(paidFence); + when(f.hosting.readCurrent(paidFence, null)).thenReturn(paidReceipt); + when(paidReceipt.gameplayAvailable()).thenReturn(true); + when(f.observer.observe(paidFence.binding())) + .thenAnswer( + invocation -> { + assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + return null; + }); + when(f.roster.read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.scope.accountId()), + org.mockito.ArgumentMatchers.any())) + .thenReturn(List.of()); + + assertTrue(f.characters().isEmpty()); + + var order = org.mockito.Mockito.inOrder(accountRepository, f.hosting, f.observer, f.roster); + order + .verify(accountRepository) + .lockCanonicalJoinAccounts(f.scope.tenantId(), f.scope.accountId()); + order.verify(accountRepository).findByAccountUuidForUpdate(f.scope.accountId()); + order.verify(f.hosting).prepareCurrentRead(f.scope.tenantId()); + order.verify(f.observer).observe(paidFence.binding()); + order + .verify(accountRepository) + .lockCanonicalJoinAccounts(f.scope.tenantId(), f.scope.accountId()); + order.verify(accountRepository).findByAccountUuidForUpdate(f.scope.accountId()); + order.verify(f.hosting).readCurrent(paidFence, null); + order + .verify(f.roster) + .read( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.eq(f.scope.accountId()), + org.mockito.ArgumentMatchers.any()); + order.verify(f.observer).observe(paidFence.binding()); + order + .verify(accountRepository) + .lockCanonicalJoinAccounts(f.scope.tenantId(), f.scope.accountId()); + order.verify(accountRepository).findByAccountUuidForUpdate(f.scope.accountId()); + order.verify(f.hosting).readCurrent(paidFence, null); + verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); + } + @Test void canonicalBootstrapCharactersReturnsEmptyOnlyAfterSuccessfulSupportedOwnerRead() { var f = canonicalJoinFixture(); @@ -2271,12 +2340,13 @@ void canonicalBootstrapCharactersRejectsTargetDriftDuringEntityReadInsteadOfRetu org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) - .thenAnswer(invocation -> { - drift.set(true); - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(UUID.randomUUID(), "Ada", 12)); - }); + .thenAnswer( + invocation -> { + drift.set(true); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Ada", 12)); + }); assertEquals( "CONNECT_SCOPE_MISMATCH", assertThrows(AuthenticationException.class, f::characters).getCode()); @@ -2291,13 +2361,14 @@ void canonicalBootstrapCharactersRechecksMembershipAfterEntityRead() { org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) - .thenAnswer(invocation -> { - f.currentMembership.setLifecycleState("INACTIVE"); - f.currentMembership.setGameplayAdmissionAllowed(false); - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(UUID.randomUUID(), "Ada", 12)); - }); + .thenAnswer( + invocation -> { + f.currentMembership.setLifecycleState("INACTIVE"); + f.currentMembership.setGameplayAdmissionAllowed(false); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Ada", 12)); + }); var failure = assertThrows(AuthenticationException.class, f::characters); assertEquals("AUTH_UNAVAILABLE", failure.getCode()); assertEquals("Bootstrap membership changed during discovery", failure.getMessage()); @@ -2318,21 +2389,22 @@ void canonicalBootstrapCharactersRejectsChangedMembershipSnapshotAfterEntityRead org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) - .thenAnswer(invocation -> { - switch (changed) { - case "version" -> - f.currentMembership.setMembershipVersion( - f.currentMembership.getMembershipVersion() + 1L); - case "generation" -> - f.currentMembership.setMembershipAuthorityGeneration( - f.currentMembership.getMembershipAuthorityGeneration() + 1L); - case "membership-id" -> f.currentMembership.setId(702L); - default -> throw new AssertionError(changed); - } - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(UUID.randomUUID(), "Withheld", 12)); - }); + .thenAnswer( + invocation -> { + switch (changed) { + case "version" -> + f.currentMembership.setMembershipVersion( + f.currentMembership.getMembershipVersion() + 1L); + case "generation" -> + f.currentMembership.setMembershipAuthorityGeneration( + f.currentMembership.getMembershipAuthorityGeneration() + 1L); + case "membership-id" -> f.currentMembership.setId(702L); + default -> throw new AssertionError(changed); + } + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 12)); + }); assertEquals( "AUTH_UNAVAILABLE", assertThrows(AuthenticationException.class, f::characters).getCode()); verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); @@ -2346,13 +2418,14 @@ void canonicalBootstrapCharactersRejectsChangedPublishedPolicyCaptureAfterEntity org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) - .thenAnswer(invocation -> { - f.policyBytes = - "changed-controlled-policy-set".getBytes(java.nio.charset.StandardCharsets.UTF_8); - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(UUID.randomUUID(), "Withheld", 12)); - }); + .thenAnswer( + invocation -> { + f.policyBytes = + "changed-controlled-policy-set".getBytes(java.nio.charset.StandardCharsets.UTF_8); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 12)); + }); assertEquals( "CONNECT_SCOPE_MISMATCH", assertThrows(AuthenticationException.class, f::characters).getCode()); @@ -2367,15 +2440,18 @@ void canonicalBootstrapCharactersRechecksCurrentEntitlementAfterEntityRead() { org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) - .thenAnswer(invocation -> { - when(f.demos.readCurrent(f.scope.tenantId())) - .thenThrow(new DataAccessResourceFailureException("controlled late billing outage")); - when(f.demos.revalidate(f.demo)) - .thenThrow(new DataAccessResourceFailureException("controlled late billing outage")); - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(UUID.randomUUID(), "Ada", 12)); - }); + .thenAnswer( + invocation -> { + when(f.demos.readCurrent(f.scope.tenantId())) + .thenThrow( + new DataAccessResourceFailureException("controlled late billing outage")); + when(f.demos.revalidate(f.demo)) + .thenThrow( + new DataAccessResourceFailureException("controlled late billing outage")); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Ada", 12)); + }); assertEquals( "ENTITLEMENT_UNAVAILABLE", assertThrows(AuthenticationException.class, f::characters).getCode()); @@ -2424,12 +2500,13 @@ public Instant instant() { org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) - .thenAnswer(invocation -> { - time.set(Instant.parse(f.scope.connectScopeExpiresAt())); - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(UUID.randomUUID(), "Ada", 12)); - }); + .thenAnswer( + invocation -> { + time.set(Instant.parse(f.scope.connectScopeExpiresAt())); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Ada", 12)); + }); assertEquals( "CONNECT_SCOPE_INVALID", assertThrows(AuthenticationException.class, f::characters).getCode()); @@ -2479,13 +2556,14 @@ void canonicalBootstrapCharactersRechecksTheBrowserRegistryAfterEntityRead() { org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) - .thenAnswer(invocation -> { - when(sessionService.isAccountSessionActive(f.account.getId(), f.bootstrap)) - .thenReturn(false); - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(UUID.randomUUID(), "Withheld", 12)); - }); + .thenAnswer( + invocation -> { + when(sessionService.isAccountSessionActive(f.account.getId(), f.bootstrap)) + .thenReturn(false); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 12)); + }); assertEquals( "CONNECT_CONTEXT_INVALID", assertThrows(AuthenticationException.class, f::characters).getCode()); @@ -2549,17 +2627,18 @@ void canonicalBootstrapCharactersRejectsUnsupportedPolicyFromLateControlledOwner // Retained resolution admits PRESEEDED_ONLY only. Change this controlled owner response // after that check to exercise the facade's own unsupported-policy refusal, not the codec. when(f.targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) - .thenAnswer(invocation -> { - when(f.target.characterCreationPolicy()).thenReturn(policy); - var published = - org.mockito.Mockito.mock( - net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence - .class); - when(published.selector()).thenReturn(invocation.getArgument(0)); - when(published.currentTarget()).thenReturn(f.target); - return published; - }); + .thenAnswer( + invocation -> { + when(f.target.characterCreationPolicy()).thenReturn(policy); + var published = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + .class); + when(published.selector()).thenReturn(invocation.getArgument(0)); + when(published.currentTarget()).thenReturn(f.target); + return published; + }); var failure = assertThrows(AuthenticationException.class, f::characters); assertEquals("REALM_UNAVAILABLE", failure.getCode()); assertEquals( @@ -2606,12 +2685,13 @@ void emailLoginOtpRequestPersistsOnlyHashedChallengeAndSendsSixDigitCode() { when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); when(accountEmailLoginChallengeRepository.findByAccountId(9L)).thenReturn(Optional.empty()); when(accountEmailLoginChallengeRepository.save(org.mockito.ArgumentMatchers.any())) - .thenAnswer(invocation -> { - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - invocation.getArgument(0); - challenge.setId(3L); - return challenge; - }); + .thenAnswer( + invocation -> { + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + invocation.getArgument(0); + challenge.setId(3L); + return challenge; + }); service.requestEmailLoginOtp("verified@example.com"); @@ -4341,10 +4421,11 @@ void candidatePasswordVerifierIsPreparedBeforeWritableOwnerTransactionBegins() { org.mockito.ArgumentMatchers.eq(65536), org.mockito.ArgumentMatchers.eq(1), org.mockito.ArgumentMatchers.any(char[].class))) - .thenAnswer(invocation -> { - candidateVerifierPrepared.set(true); - return "prepared-candidate-verifier"; - }); + .thenAnswer( + invocation -> { + candidateVerifierPrepared.set(true); + return "prepared-candidate-verifier"; + }); org.mockito.Mockito.doAnswer( invocation -> { assertTrue( @@ -4429,16 +4510,17 @@ void passwordResetIssuanceFenceOverflowStopsBeforeTokenPasswordOrEventMutation() org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) - .thenAnswer(invocation -> - sourceChanges.participate( - invocation.getArgument(0), - invocation.getArgument(1), - invocation.getArgument(2), - invocation.getArgument(3), - invocation.getArgument(4), - invocation.getArgument(5), - invocation.getArgument(6), - invocation.getArgument(7))); + .thenAnswer( + invocation -> + sourceChanges.participate( + invocation.getArgument(0), + invocation.getArgument(1), + invocation.getArgument(2), + invocation.getArgument(3), + invocation.getArgument(4), + invocation.getArgument(5), + invocation.getArgument(6), + invocation.getArgument(7))); org.springframework.transaction.support.TransactionSynchronizationManager .setActualTransactionActive(true); @@ -4630,9 +4712,10 @@ void sendUsernameReminderContainsDeliveryFailure() { "demo@example.com")); assertTrue( appender.list.stream() - .anyMatch(event -> - "Recovery email delivery failed; cause=RuntimeException" - .equals(event.getFormattedMessage()))); + .anyMatch( + event -> + "Recovery email delivery failed; cause=RuntimeException" + .equals(event.getFormattedMessage()))); assertFalse( appender.list.stream() .anyMatch(event -> event.getFormattedMessage().contains("SMTP failure"))); From 41e32304dd8bbc554652d169452ca5c85a22fe8b Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 25 Nov 2026 21:33:21 +1300 Subject: [PATCH 03/14] Verify paid JOIN and discovery on the exact Account comparison --- .../player-access-and-session.md | 2 + ...rUuidEntityCompositionIntegrationTest.java | 234 ++++++++++++++---- ...CurrentSourcesPostgresIntegrationTest.java | 22 +- ...nonicalHostingSubscriptionTestFixture.java | 79 +++--- .../service/impl/AccountServiceImplTest.java | 4 + 5 files changed, 254 insertions(+), 87 deletions(-) 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 c9888197af..620724f4a7 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -192,6 +192,8 @@ The unregistered receiver includes explicit original closure under the existing The Account NEW source now prepares an explicit paid-hosting composition alongside DEMO. Account selects the current source head, prepares the existing hosting owner's exact fence in an Account-first writable SERIALIZABLE transaction, observes the real bounded Stripe SDK outside SQL, then reconstructs that owner on the decisive transaction's exact connection and rereads its current receipt. Opaque owner-bound preparation/observation carries no caller-selected source authority; missing paid composition, changed heads, unresolved provider facts and expired authority fail closed without DEMO fallback. The original lease retains the same five source subtrees and is additionally capped at paid authority expiry. First finalization rereads complete paid authority through the original physical-COMMIT executor and exact-compares the original lease; metadata, cleanup and terminal receipt recovery retain their narrower current-caller checks. The [canonical session contract](../../architecture/system-architecture-session-behavior.md#canonical-public-production-new-admission) remains normative. Seven new PostgreSQL source/composition definitions cover actual owner reads, missing composition/observation, no provider read in SQL, provider disagreement/expiry, changed heads, authenticated acquisition/finalization/recovery and writer exclusion through physical COMMIT. On the local paid-source postimage over baseline `cee9af5e75f2f84140efdc6f9e902794cf61986e`, the focused gate passes all 87 selected unit cases with zero failures, errors or skips: four lease-owner, 26 original-COMMIT executor, 40 ACK-receipt executor, eleven hosting-repository and six hosting-policy cases. Full integration compilation includes the new paid fixture; enabled main/test/integration SpotBugs, Java formatting and Markdown lint pass. The initial gate failed on one unnecessary new SpotBugs suppression, removed before the successful rerun. Physical PostgreSQL/Redis execution remains unrun because Docker is unavailable, and external link checking remains unrun. Compilation and static analysis do not replace physical proof. Controlled provider transport, reverse Game Session evidence and test custody do not establish live Stripe, an admitted binding, production registration or available `PLAY`/`LOOK`. +The original paid-provider observation freshness contract remains held. The last decisive Account source read rejects an expired paid receipt, but does not establish that the original observation remains fresh through physical COMMIT and ACK. That crossing is still unqualified; the focused checks above are not proof of it. + Local negative-continuation preparation retains irreversible original-candidate abandonment, a persistent non-admitting Redis closure, separately authenticated Account negative resolution, and genuine ordinary-local or installed frozen-cohort issuer release/retirement. R1044 executes 33 selected Game Session cases (30 pass, two historical-fixture failures and one PostgreSQL startup failure) and nine Account cases (five pass, two ordinary terminal-retirement failures, one inaccessible test-handle failure and one Redis startup failure). The run's failed aggregate remains retained; later corrections are qualified by the separately attributed receiving results below. Pre-anchor or superseded issued work without an installed revision owner remains unresolved and non-admitting under Gameplay ownership. Existing holds authorize no old-key cleanup, invented ordinary registration or Redis-absence proof; this does not waive the separately held recovery scope. Implementing that held category requires an exact authority/contract proposal. Controlled qualification, upstream source and test PKI do not establish production custody, registration, activation or gameplay admission. For the PLAYER_CREATED correction, R1069 passed 67/68 selected cases; its single failure was an initial Redis connection refusal of unknown cause. R1074 then passed 122/126, with three Account negative-composition failures because V1051 omitted inherited `NEVER_DISPATCHED` branches and one World cleanup failure that could mask the primary exception; the underlying connection-refusal cause remains unknown. Corrected V1051 retains the inherited statuses and branch without editing source-parent migrations. On corrected source `e93aac69277af1fe39afe196db1546cf5eb4737a`, R1077 separately passes all 15 selected cases (eight Game Session region-owner, three Account final-admission, three Account negative-composition and one World receipt case), plus selected static, generation and documentation checks; source hashes are stable and Spotless made no formatter changes. R1082 is local proof only, with its two-file test preparation subsequently retained at `c8f16db50e27a754e1d80a94d09c8d8f32f2ee4f` on genuine parent `d2e3a21a31419680e68ab2da6ea7e808e4efd83c`: against that V1050.4 parent, before introducing corrected V1051, both ordinary and installed parameter cases pass while preserving release/retirement records, old columns and `xmin`, Flyway history/checksums, issuer/closure Redis and exact retry after Account restart. R1079 remains a failed pre-migration proof setup because it repeated preparation after cleanup and supplies no migration credit. R1086 subsequently passes all 31 selected receiving cases on reconciled source `b7143cf062699bca230f4c2cbec03f9da651a380`: Account handler and bounded-readback units, Game Session authenticated-session and candidate units, three actual Account final-admission compositions and both Entity namespace concurrency/scope-refusal regressions. All selected generation, enabled static analysis, formatting and documentation checks pass, with no service formatter delta. R1089 separately passes 26 native executions on the receiving child (eight final-owner and 18 parameterized Account definitive-abort cases), including the new explicit REQUIRED-delete refusal. Positive-source R1092 subsequently passes 26 executions (13 reader units, four reader-service units and nine native final-owner cases) after separating clock unavailability from retained-source conflict and tightening every refusal assertion. Its new native case confirms the existing committed-receipt delete guard, unchanged retained state through clock lag and successful readback when the clock catches up; R1093 separately executes all 12 selected descendant native cases (nine final-owner and three actual Account compositions) successfully, with selected static analysis and no source/formatter changes. Its aggregate remains failed because Markdown lint rejected the added HTML link anchor; the Markdown-heading correction and documentation recovery retain separate attribution. These separate results do not establish an all-126 clean aggregate, current CI, production/default registration, PKI custody or activation. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java index 547f5b69bd..80cfdb3847 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; import io.grpc.ManagedChannel; import io.grpc.Server; import io.grpc.ServerInterceptors; @@ -32,8 +33,11 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import javax.sql.DataSource; import net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient; import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; @@ -127,6 +131,7 @@ import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; @@ -261,8 +266,8 @@ void bootstrapCharactersUseCanonicalOwnersAndPersistedLevelsAcrossHttpAndTwoMtls TestAccount ownerB = registerAccount("uuid-owner-b-" + suffix); assertThat(ownerA.accountUuid()).isNotEqualTo(ownerB.accountUuid()); configureCanonicalAccountOwners(); - initializeMemberAuthority(ownerA); - initializeMemberAuthority(ownerB); + initializeMemberAuthority(ownerA, SOURCE.target().tenantUuid()); + initializeMemberAuthority(ownerB, SOURCE.target().tenantUuid()); String tokenA = issuePlayerBootstrap(ownerA); String tokenB = issuePlayerBootstrap(ownerB); String scopeA = discoverConnectScope(ownerA, tokenA); @@ -385,36 +390,119 @@ void retainedNumericSelectorIsRefusedByOrdinaryRpcWithoutRewritingItsRow() throw assertThat(retainedNumericOwnerRow(entity)).isEqualTo(retainedBefore); } + @org.junit.jupiter.api.Nested + class PaidJoinDiscoveryComposition { + @org.junit.jupiter.api.io.TempDir Path checkoutDirectory; + @Autowired private DataSource paidCompositionDataSource; + + @org.junit.jupiter.api.Test + @org.springframework.test.annotation.DirtiesContext + void paidJoinReplayAndCharacterDiscoveryCompleteConcurrently() throws Exception { + var source = AccountBootstrapRosterFixture.create(); + var target = accountTarget(source); + String suffix = UUID.randomUUID().toString().substring(0, 8); + var first = registerAccount("paid-pair-a-" + suffix); + var second = registerAccount("paid-pair-b-" + suffix); + boolean firstIsPayer = first.accountUuid().compareTo(second.accountUuid()) < 0; + var payer = firstIsPayer ? first : second; + var caller = firstIsPayer ? second : first; + assertThat(payer.accountUuid().compareTo(caller.accountUuid())).isNegative(); + var hosting = + CanonicalHostingSubscriptionTestFixture.createForExistingTenant( + paidCompositionDataSource, + accounts.findByAccountUuid(payer.accountUuid()).orElseThrow(), + tenantEvidence(target, 102L)) + .withCheckoutDirectory(checkoutDirectory); + assertThat(hosting.completeFirstInvoice("password123").outcome().name()) + .isEqualTo("COMMITTED"); + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> accountSources.initializeIssuerIfAbsent("firemud-account-service")); + initializeMemberAuthority(caller, target.canonicalTenantId()); + + var observer = Mockito.mock(StripeHostingSubscriptionObserver.class); + var concurrentObservations = new CountDownLatch(2); + var observeTogether = new java.util.concurrent.atomic.AtomicBoolean(); + var firstObservationByWorker = ThreadLocal.withInitial(() -> true); + Mockito.when(observer.observe(Mockito.any())) + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + if (observeTogether.get() && firstObservationByWorker.get()) { + firstObservationByWorker.set(false); + concurrentObservations.countDown(); + if (!concurrentObservations.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Paid entrypoints did not overlap outside SQL"); + } + } + synchronized (hosting) { + return hosting.observer().observe(invocation.getArgument(0)); + } + }); + configureCanonicalAccountOwners( + controlledAccountTargets(target, source), + hosting.lifecycleRepository(), + observer, + hosting.clock()); + var roster = Mockito.mock(AccountBootstrapRosterReadClient.class); + UUID actorId = UUID.randomUUID(); + Mockito.when(roster.read(Mockito.any(), Mockito.eq(caller.accountUuid()), Mockito.any())) + .thenReturn( + List.of(new AccountBootstrapRosterReadClient.Actor(actorId, "Fixture actor", 7))); + facade.setAccountBootstrapRosterReadClient(roster); + String token = issuePlayerBootstrap(caller); + String scope = discoverConnectScope(caller, token, target); + var request = new JoinPublicProductionRequest(scope, UUID.randomUUID().toString()); + var joined = facade.joinPublicProduction(token, request); + assertThat(joined.success()).isTrue(); + assertThat(joined.tenantId()).isEqualTo(target.canonicalTenantId()); + + var ready = new CountDownLatch(2); + var go = new CountDownLatch(1); + var workers = Executors.newFixedThreadPool(2); + try { + var replay = + workers.submit(() -> { + ready.countDown(); + if (!go.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("Start not released"); + return facade.joinPublicProduction(token, request); + }); + var discovery = + workers.submit(() -> { + ready.countDown(); + if (!go.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("Start not released"); + return facade.listBootstrapCharacters( + token, target.worldSlug(), target.realmSlug(), scope); + }); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + observeTogether.set(true); + go.countDown(); + var retained = replay.get(30, TimeUnit.SECONDS); + assertThat(retained.success()).isTrue(); + assertThat(retained.tenantId()).isEqualTo(joined.tenantId()); + assertThat(retained.membershipVersion()).isEqualTo(joined.membershipVersion()); + assertThat(discovery.get(30, TimeUnit.SECONDS)) + .singleElement() + .satisfies(actor -> { + assertThat(actor.characterId()).isEqualTo(actorId.toString()); + assertThat(actor.characterName()).isEqualTo("Fixture actor"); + assertThat(actor.level()).isEqualTo(7); + }); + assertThat(concurrentObservations.getCount()).isZero(); + Mockito.verify(roster).read(Mockito.any(), Mockito.eq(caller.accountUuid()), Mockito.any()); + } finally { + go.countDown(); + workers.shutdownNow(); + assertThat(workers.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + } + private void configureCanonicalAccountOwners() { var transaction = new TransactionTemplate(transactionManager); var target = accountTarget(); - var creationRequest = UUID.randomUUID(); - var operation = UUID.randomUUID(); - String key = "b-" + operation.toString().replace("-", ""); - String digest = - GameTenantCreationDigest.requestDigest( - TEST_NAMESPACE, creationRequest, key, "Bootstrap composition", null); - long rowId = 101L; - var source = - new FreshTenantCreationEvidence( - 1, - TEST_NAMESPACE, - creationRequest, - operation, - digest, - target.canonicalTenantId(), - rowId, - key, - "NEW_GAME_ROW", - GameTenantCreationDigest.evidenceDigest( - TEST_NAMESPACE, - creationRequest, - operation, - digest, - target.canonicalTenantId(), - rowId, - key, - "NEW_GAME_ROW")); + var source = tenantEvidence(target, 101L); transaction.executeWithoutResult(status -> { tenants.importVerified(source); generations.initializeTenantIfAbsent(target.canonicalTenantId()); @@ -438,7 +526,42 @@ private void configureCanonicalAccountOwners() { var targets = controlledAccountTargets(target); var hosting = Mockito.mock(AccountHostingSubscriptionLifecycleRepository.class); var observer = Mockito.mock(StripeHostingSubscriptionObserver.class); - var clock = Clock.systemUTC(); + configureCanonicalAccountOwners(targets, hosting, observer, Clock.systemUTC()); + } + + private static FreshTenantCreationEvidence tenantEvidence(Target target, long rowId) { + var creationRequest = UUID.randomUUID(); + var operation = UUID.randomUUID(); + String key = "b-" + operation.toString().replace("-", ""); + String digest = + GameTenantCreationDigest.requestDigest( + TEST_NAMESPACE, creationRequest, key, "Bootstrap composition", null); + return new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + creationRequest, + operation, + digest, + target.canonicalTenantId(), + rowId, + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + creationRequest, + operation, + digest, + target.canonicalTenantId(), + rowId, + key, + "NEW_GAME_ROW")); + } + + private void configureCanonicalAccountOwners( + CanonicalGameplayAdmissionDecisionReadClient targets, + AccountHostingSubscriptionLifecycleRepository hosting, + StripeHostingSubscriptionObserver observer, + Clock clock) { var entitlement = new AccountPublicBootstrapEntitlementOwner( tenantEvents, @@ -474,6 +597,11 @@ private void configureCanonicalAccountOwners() { } private CanonicalGameplayAdmissionDecisionReadClient controlledAccountTargets(Target target) { + return controlledAccountTargets(target, SOURCE); + } + + private CanonicalGameplayAdmissionDecisionReadClient controlledAccountTargets( + Target target, AccountBootstrapRosterFixture.Fixture source) { var client = Mockito.mock(CanonicalGameplayAdmissionDecisionReadClient.class); Mockito.when(client.listVisiblePublicProductionAdmissionTargets(Mockito.any())) .thenAnswer(invocation -> { @@ -504,7 +632,7 @@ private CanonicalGameplayAdmissionDecisionReadClient controlledAccountTargets(Ta CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); Mockito.when(published.selector()).thenReturn(request); Mockito.when(published.currentTarget()).thenReturn(target); - Mockito.when(published.sourceEvidence()).thenReturn(ownerEvidence(request)); + Mockito.when(published.sourceEvidence()).thenReturn(ownerEvidence(request, source)); var world = Mockito.mock(WorldCanonicalInstanceLifecycleEvidence.class); Mockito.when(world.lifecycleStatus()).thenReturn("ACTIVE"); Mockito.when(world.lifecycleEpoch()).thenReturn(target.activeWorldEpoch()); @@ -514,17 +642,21 @@ private CanonicalGameplayAdmissionDecisionReadClient controlledAccountTargets(Ta return client; } - private void initializeMemberAuthority(TestAccount account) { + private void initializeMemberAuthority(TestAccount account, UUID tenantId) { new TransactionTemplate(transactionManager) .executeWithoutResult(status -> generations.initialize( AccountAuthorityGenerationRepository.AuthorityScope.membership( - account.accountUuid(), SOURCE.target().tenantUuid()))); + account.accountUuid(), tenantId))); } private static Target accountTarget() { - var target = SOURCE.target(); - var proof = SOURCE.evidence().gameSessionOwnerProof(); + return accountTarget(SOURCE); + } + + private static Target accountTarget(AccountBootstrapRosterFixture.Fixture source) { + var target = source.target(); + var proof = source.evidence().gameSessionOwnerProof(); var hold = proof.holdIdentity(); var request = hold.request(); return new Target( @@ -564,7 +696,13 @@ private static Target accountTarget() { private static CanonicalGameplayRosterOwnerReadEvidence ownerEvidence( CanonicalGameplayRosterOwnerReadEvidence.Request request) { - var base = SOURCE.evidence().request(); + return ownerEvidence(request, SOURCE); + } + + private static CanonicalGameplayRosterOwnerReadEvidence ownerEvidence( + CanonicalGameplayRosterOwnerReadEvidence.Request request, + AccountBootstrapRosterFixture.Fixture source) { + var base = source.evidence().request(); var expected = new CanonicalGameplayRosterOwnerReadEvidence.Request( request.requestUuid(), @@ -585,9 +723,9 @@ private static CanonicalGameplayRosterOwnerReadEvidence ownerEvidence( throw new IllegalArgumentException("Controlled owner target mismatch"); return new CanonicalGameplayRosterOwnerReadEvidence( request, - SOURCE.target().admissionPointerSnapshotDigest(), - SOURCE.evidence().gameSessionOwnerProof(), - SOURCE.evidence().publishedPolicySetEvidence()); + source.target().admissionPointerSnapshotDigest(), + source.evidence().gameSessionOwnerProof(), + source.evidence().publishedPolicySetEvidence()); } private TestAccount registerAccount(String username) throws Exception { @@ -630,14 +768,19 @@ private String issuePlayerBootstrap(TestAccount account) throws Exception { } private String discoverConnectScope(TestAccount account, String token) throws Exception { + return discoverConnectScope(account, token, accountTarget()); + } + + private String discoverConnectScope(TestAccount account, String token, Target target) + throws Exception { var request = HttpRequest.newBuilder( URI.create( accountBaseUrl() + "/auth/bootstrap/worlds/" - + SOURCE.target().worldSlug() + + target.worldSlug() + "/realms?tenantSlug=" - + accountTarget().tenantSlug())) + + target.tenantSlug())) .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) .GET() .build(); @@ -645,9 +788,8 @@ private String discoverConnectScope(TestAccount account, String token) throws Ex if (response.statusCode() != 200) { // Preserve the HTTP assertion while exposing an owner/proxy exception otherwise hidden by // the public INTERNAL_ERROR projection. This uses the same actual caller and owner setup. - org.assertj.core.api.Assertions.assertThatCode(() -> - facade.listBootstrapRealms( - token, accountTarget().tenantSlug(), SOURCE.target().worldSlug())) + org.assertj.core.api.Assertions.assertThatCode( + () -> facade.listBootstrapRealms(token, target.tenantSlug(), target.worldSlug())) .as("REALMS owner composition after HTTP response: %s", response.body()) .doesNotThrowAnyException(); } @@ -655,13 +797,13 @@ token, accountTarget().tenantSlug(), SOURCE.target().worldSlug())) var realms = jsonMapper.readTree(response.body()).path("data"); assertThat(realms.size()).isEqualTo(1); assertThat(realms.get(0).path("tenantId").asText()) - .isEqualTo(SOURCE.target().tenantUuid().toString()); + .isEqualTo(target.canonicalTenantId().toString()); String scope = realms.get(0).path("connectScopeId").asText(); var claims = jwtUtil.parseToken(scope).getPayload(); assertThat(claims.getSubject()).isEqualTo(account.accountUuid().toString()); assertThat(claims.get("scopeDigestVersion", Number.class).longValue()).isEqualTo(2L); assertThat(claims.get("tenantId", String.class)) - .isEqualTo(SOURCE.target().tenantUuid().toString()); + .isEqualTo(target.canonicalTenantId().toString()); return scope; } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index 80a0bbb036..64255954dc 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -425,17 +425,17 @@ void paidSourceWithoutItsConcreteCompositionOrObservationNeverFallsBackToDemo() void paidObservationCannotRunInsideThePreparingAccountTransaction() throws Exception { PaidFixture paid = newPaidFixture(null); int reads = paid.hosting().transport().reads(); - assertThatThrownBy(() -> - paid.caller() - .inCurrentSources(sources -> - sources - .prepareCurrentPublicProductionNew( - paid.hosting().tenantId(), - paid.caller().committedCandidate.identity().tokenJti(), - paid.caller().committedCandidate, - paid.hosting().admissionPaidSource()) - .observeOutsideSql())) - .isInstanceOf(IllegalStateException.class); + paid.caller() + .inCurrentSources(sources -> { + var prepared = + sources.prepareCurrentPublicProductionNew( + paid.hosting().tenantId(), + paid.caller().committedCandidate.identity().tokenJti(), + paid.caller().committedCandidate, + paid.hosting().admissionPaidSource()); + assertThatThrownBy(prepared::observeOutsideSql).isInstanceOf(IllegalStateException.class); + return null; + }); assertThat(paid.hosting().transport().reads()).isEqualTo(reads); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java index d5688b845d..c9e221e5c6 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java @@ -118,22 +118,36 @@ public final class CanonicalHostingSubscriptionTestFixture { private CanonicalHostingSubscriptionTestFixture() {} public static Fixture create(DataSource source) { - return createInternal(source, null, "prod"); + return createInternal(source, null, "prod", null); } /** Uses the caller's explicit workload namespace without changing controlled source custody. */ public static Fixture create(DataSource source, String namespace) { - return createInternal(source, null, namespace); + return createInternal(source, null, namespace, null); } /** Reuses the exact persisted Account of a genuine actor/authentication composition. */ public static Fixture create(DataSource source, Account account) { return createInternal( - source, Objects.requireNonNull(account, "persisted Account required"), "prod"); + source, Objects.requireNonNull(account, "persisted Account required"), "prod", null); + } + + /** Seeds paid receipt state for the exact tenant carried by a separate test composition. */ + public static Fixture createForExistingTenant( + DataSource source, Account account, FreshTenantCreationEvidence tenantSource) { + Objects.requireNonNull(tenantSource, "exact fixture tenant evidence required"); + return createInternal( + source, + Objects.requireNonNull(account, "persisted Account required"), + tenantSource.targetNamespace(), + tenantSource); } private static Fixture createInternal( - DataSource source, Account existingAccount, String namespace) { + DataSource source, + Account existingAccount, + String namespace, + FreshTenantCreationEvidence existingTenantSource) { Objects.requireNonNull(source, "migrated Account datasource is required"); JdbcTemplate jdbc = new JdbcTemplate(source); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); @@ -159,33 +173,9 @@ private static Fixture createInternal( long accountId = accountRow.get("id", Long.class); UUID accountUuid = accountRow.get("account_uuid", UUID.class); - UUID tenantId = UUID.randomUUID(); - UUID tenantCreateRequest = UUID.randomUUID(); - UUID tenantCreateOperation = UUID.randomUUID(); - String tenantKey = "hosting-fixture-game-" + row; - String tenantRequestDigest = - GameTenantCreationDigest.requestDigest( - namespace, tenantCreateRequest, tenantKey, "Controlled hosting", "Storage only"); var tenantSource = - new FreshTenantCreationEvidence( - 1, - namespace, - tenantCreateRequest, - tenantCreateOperation, - tenantRequestDigest, - tenantId, - row, - tenantKey, - "NEW_GAME_ROW", - GameTenantCreationDigest.evidenceDigest( - namespace, - tenantCreateRequest, - tenantCreateOperation, - tenantRequestDigest, - tenantId, - row, - tenantKey, - "NEW_GAME_ROW")); + existingTenantSource == null ? freshTenantSource(namespace, row) : existingTenantSource; + UUID tenantId = tenantSource.canonicalTenantId(); in( transaction, () -> { @@ -323,6 +313,35 @@ private static Fixture createInternal( } /** Separate factory for protected HTTPS owner tests that supply their own genuine actor. */ + private static FreshTenantCreationEvidence freshTenantSource(String namespace, long row) { + UUID tenantId = UUID.randomUUID(); + UUID tenantCreateRequest = UUID.randomUUID(); + UUID tenantCreateOperation = UUID.randomUUID(); + String tenantKey = "hosting-fixture-game-" + row; + String tenantRequestDigest = + GameTenantCreationDigest.requestDigest( + namespace, tenantCreateRequest, tenantKey, "Controlled hosting", "Storage only"); + return new FreshTenantCreationEvidence( + 1, + namespace, + tenantCreateRequest, + tenantCreateOperation, + tenantRequestDigest, + tenantId, + row, + tenantKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + namespace, + tenantCreateRequest, + tenantCreateOperation, + tenantRequestDigest, + tenantId, + row, + tenantKey, + "NEW_GAME_ROW")); + } + public static Fixture createAwaitingPayment( DataSource source, Account account, Path checkoutDirectory) { var fixture = create(source, account); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 0724d22cfa..5f88336359 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -998,6 +998,8 @@ void canonicalCommittedReplayPreservesReceiptWhenCurrentGameplayIsUnavailable(St .lockCanonicalJoinAccounts(f.scope.tenantId(), f.scope.accountId()); order.verify(accountRepository).findByAccountUuidForUpdate(f.scope.accountId()); order.verify(f.hosting).readCurrent(paidFence, null); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.times(3)) + .findByAccountUuidForUpdate(f.scope.accountId()); } org.mockito.Mockito.verify(f.terminal) @@ -2166,6 +2168,8 @@ void paidBootstrapCharactersLocksCanonicalAccountsBeforeEveryHostingRead() { .lockCanonicalJoinAccounts(f.scope.tenantId(), f.scope.accountId()); order.verify(accountRepository).findByAccountUuidForUpdate(f.scope.accountId()); order.verify(f.hosting).readCurrent(paidFence, null); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.times(3)) + .findByAccountUuidForUpdate(f.scope.accountId()); verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); } From 2f5b933f82d5cdef4ee602de8876c6f37e30b7a0 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 25 Nov 2026 22:31:42 +1300 Subject: [PATCH 04/14] Use a distinct canonical tenant in the paid JOIN fixture --- ...rUuidEntityCompositionIntegrationTest.java | 3 ++- .../common/testing/AuthoringFixtures.java | 23 +++++++++++-------- .../AccountBootstrapRosterFixture.java | 12 +++++++++- 3 files changed, 27 insertions(+), 11 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java index 80cfdb3847..88ee4cb497 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java @@ -398,8 +398,9 @@ class PaidJoinDiscoveryComposition { @org.junit.jupiter.api.Test @org.springframework.test.annotation.DirtiesContext void paidJoinReplayAndCharacterDiscoveryCompleteConcurrently() throws Exception { - var source = AccountBootstrapRosterFixture.create(); + var source = AccountBootstrapRosterFixture.create(UUID.randomUUID()); var target = accountTarget(source); + assertThat(target.canonicalTenantId()).isNotEqualTo(SOURCE.target().tenantUuid()); String suffix = UUID.randomUUID().toString().substring(0, 8); var first = registerAccount("paid-pair-a-" + suffix); var second = registerAccount("paid-pair-b-" + suffix); diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java index 09a9931c06..147fc0fd86 100644 --- a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java @@ -48,7 +48,13 @@ public final class AuthoringFixtures { private AuthoringFixtures() {} public static WorldDraftTerminalReadEvidence.Request freshGraphRequest() throws Exception { - DraftCommitBinding draft = freshGraphBinding(); + return freshGraphRequest(TENANT_ID); + } + + /** Uses a distinct tenant while preserving the same controlled graph topology. */ + public static WorldDraftTerminalReadEvidence.Request freshGraphRequest(UUID tenantId) + throws Exception { + DraftCommitBinding draft = freshGraphBinding(tenantId); return new WorldDraftTerminalReadEvidence.Request( 1, "test", uuid("33333333-3333-4333-8333-333333333333"), accountBinding(draft)); } @@ -217,7 +223,7 @@ public static byte[] accountBinding(DraftCommitBinding draft) { COMMIT_ID, FENCE_ID, ACTOR_ID, - TENANT_ID, + draft.target().canonicalTenantId(), VERSION_ID, "base-1", "0", @@ -242,7 +248,7 @@ public static ObjectNode receipt( var account = request.accountBinding(); var selector = Map.of( - "tenantId", TENANT_ID.toString(), + "tenantId", draft.target().canonicalTenantId().toString(), "versionId", VERSION_ID.toString(), "roomTemplateId", ROOM_TEMPLATE_ID.toString()); String accountBindingDigest = sha256(request.originalAccountBinding()); @@ -255,7 +261,7 @@ public static ObjectNode receipt( account.fenceId(), accountBindingDigest, draft.digest(), - TENANT_ID, + draft.target().canonicalTenantId(), VERSION_ID, ROOM_TEMPLATE_ID, graphDigest); @@ -370,7 +376,7 @@ private static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( } } - private static DraftCommitBinding freshGraphBinding() throws Exception { + private static DraftCommitBinding freshGraphBinding(UUID tenantId) throws Exception { List> familyCounts = List.of( insertionOrderedMap("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), @@ -384,17 +390,16 @@ private static DraftCommitBinding freshGraphBinding() throws Exception { String declaration = JSON.writeValueAsString( insertionOrderedMap( - "tenantId", TENANT_ID.toString(), + "tenantId", tenantId.toString(), "versionId", VERSION_ID.toString(), "startLocation", insertionOrderedMap( - "tenantId", TENANT_ID.toString(), + "tenantId", tenantId.toString(), "versionId", VERSION_ID.toString(), "roomTemplateId", ROOM_TEMPLATE_ID.toString()), "familyCounts", familyCounts)); return DraftCommitBinding.create( - new TargetProof( - TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + new TargetProof(tenantId, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), REQUEST_ID, COMMIT_ID, "base-1", diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java index ecd1b38212..09f19c33e8 100644 --- a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java @@ -21,6 +21,7 @@ import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldDraftTerminalReadEvidence; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; @@ -51,7 +52,16 @@ public record Fixture( } public static Fixture create() throws Exception { - var account = AuthoringFixtures.freshGraphRequest().accountBinding(); + return create(AuthoringFixtures.freshGraphRequest()); + } + + /** Uses independent canonical owner evidence for a separately seeded tenant. */ + public static Fixture create(UUID canonicalTenantId) throws Exception { + return create(AuthoringFixtures.freshGraphRequest(canonicalTenantId)); + } + + private static Fixture create(WorldDraftTerminalReadEvidence.Request owner) throws Exception { + var account = owner.accountBinding(); var draft = DraftCommitBinding.fromStored( new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); From 107eeb886058e3a459e06b7e966d3281fe71690a Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 25 Nov 2026 23:04:04 +1300 Subject: [PATCH 05/14] Import the authoring evidence type in the paid test fixture --- .../bootstrap/AccountBootstrapRosterFixture.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java index 09f19c33e8..f72faaaa13 100644 --- a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java @@ -9,6 +9,7 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; @@ -21,7 +22,6 @@ import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; -import net.firedevops.firemud.common.world.WorldDraftTerminalReadEvidence; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; import net.firedevops.firemud.entitymanagement.v1.AccountBootstrapRosterReadRequest; From efad5f728ea024d3ac303e225402c3b095a84c14 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 25 Nov 2026 23:26:34 +1300 Subject: [PATCH 06/14] Separate the paid fixture request from the attestation owner --- .../bootstrap/AccountBootstrapRosterFixture.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java index f72faaaa13..717e5af21f 100644 --- a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java @@ -60,8 +60,9 @@ public static Fixture create(UUID canonicalTenantId) throws Exception { return create(AuthoringFixtures.freshGraphRequest(canonicalTenantId)); } - private static Fixture create(WorldDraftTerminalReadEvidence.Request owner) throws Exception { - var account = owner.accountBinding(); + private static Fixture create(WorldDraftTerminalReadEvidence.Request draftTerminal) + throws Exception { + var account = draftTerminal.accountBinding(); var draft = DraftCommitBinding.fromStored( new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); From 0e3789c6ef980c67e35bd1f212c1a437bbf35ce9 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 26 Nov 2026 00:02:02 +1300 Subject: [PATCH 07/14] Align the paid JOIN fixture clock with issued bootstrap claims --- ...tstrapCharacterUuidEntityCompositionIntegrationTest.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java index 88ee4cb497..384a5f4dc7 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java @@ -451,6 +451,12 @@ void paidJoinReplayAndCharacterDiscoveryCompleteConcurrently() throws Exception List.of(new AccountBootstrapRosterReadClient.Actor(actorId, "Fixture actor", 7))); facade.setAccountBootstrapRosterReadClient(roster); String token = issuePlayerBootstrap(caller); + // HTTP issuance uses the wall clock; keep the retained paid and scope fixtures on one clock. + hosting.clock().advanceToAtLeast(Clock.systemUTC().instant()); + var bootstrapClaims = jwtUtil.parseToken(token).getPayload(); + assertThat(hosting.clock().instant()) + .isAfterOrEqualTo(bootstrapClaims.getIssuedAt().toInstant()) + .isBefore(bootstrapClaims.getExpiration().toInstant()); String scope = discoverConnectScope(caller, token, target); var request = new JoinPublicProductionRequest(scope, UUID.randomUUID().toString()); var joined = facade.joinPublicProduction(token, request); From b527a3f30037e29e388e0c4d08ebfa5e0388ce32 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 27 Nov 2026 21:18:26 +1300 Subject: [PATCH 08/14] Bound paid NEW admission by the entitlement freshness window --- .../player-access-and-session.md | 2 + ...ccountGameplayAdmissionCurrentSources.java | 3 +- .../AccountGameplayAdmissionPaidSource.java | 25 ++++-- ...CurrentSourcesPostgresIntegrationTest.java | 76 ++++++++++++++----- ...nonicalHostingSubscriptionTestFixture.java | 2 +- 5 files changed, 83 insertions(+), 25 deletions(-) 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 620724f4a7..1993a2348d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -192,6 +192,8 @@ The unregistered receiver includes explicit original closure under the existing The Account NEW source now prepares an explicit paid-hosting composition alongside DEMO. Account selects the current source head, prepares the existing hosting owner's exact fence in an Account-first writable SERIALIZABLE transaction, observes the real bounded Stripe SDK outside SQL, then reconstructs that owner on the decisive transaction's exact connection and rereads its current receipt. Opaque owner-bound preparation/observation carries no caller-selected source authority; missing paid composition, changed heads, unresolved provider facts and expired authority fail closed without DEMO fallback. The original lease retains the same five source subtrees and is additionally capped at paid authority expiry. First finalization rereads complete paid authority through the original physical-COMMIT executor and exact-compares the original lease; metadata, cleanup and terminal receipt recovery retain their narrower current-caller checks. The [canonical session contract](../../architecture/system-architecture-session-behavior.md#canonical-public-production-new-admission) remains normative. Seven new PostgreSQL source/composition definitions cover actual owner reads, missing composition/observation, no provider read in SQL, provider disagreement/expiry, changed heads, authenticated acquisition/finalization/recovery and writer exclusion through physical COMMIT. On the local paid-source postimage over baseline `cee9af5e75f2f84140efdc6f9e902794cf61986e`, the focused gate passes all 87 selected unit cases with zero failures, errors or skips: four lease-owner, 26 original-COMMIT executor, 40 ACK-receipt executor, eleven hosting-repository and six hosting-policy cases. Full integration compilation includes the new paid fixture; enabled main/test/integration SpotBugs, Java formatting and Markdown lint pass. The initial gate failed on one unnecessary new SpotBugs suppression, removed before the successful rerun. Physical PostgreSQL/Redis execution remains unrun because Docker is unavailable, and external link checking remains unrun. Compilation and static analysis do not replace physical proof. Controlled provider transport, reverse Game Session evidence and test custody do not establish live Stripe, an admitted binding, production registration or available `PLAY`/`LOOK`. +The unregistered Account paid NEW composition requires an explicit deployment entitlement clock-skew bound below 15 seconds. The focused fixture supplies a synthetic bound. Production registration remains held until deployment supplies the validated entitlement freshness configuration. + The original paid-provider observation freshness contract remains held. The last decisive Account source read rejects an expired paid receipt, but does not establish that the original observation remains fresh through physical COMMIT and ACK. That crossing is still unqualified; the focused checks above are not proof of it. Local negative-continuation preparation retains irreversible original-candidate abandonment, a persistent non-admitting Redis closure, separately authenticated Account negative resolution, and genuine ordinary-local or installed frozen-cohort issuer release/retirement. R1044 executes 33 selected Game Session cases (30 pass, two historical-fixture failures and one PostgreSQL startup failure) and nine Account cases (five pass, two ordinary terminal-retirement failures, one inaccessible test-handle failure and one Redis startup failure). The run's failed aggregate remains retained; later corrections are qualified by the separately attributed receiving results below. Pre-anchor or superseded issued work without an installed revision owner remains unresolved and non-admitting under Gameplay ownership. Existing holds authorize no old-key cleanup, invented ordinary registration or Redis-absence proof; this does not waive the separately held recovery scope. Implementing that held category requires an exact authority/contract proposal. Controlled qualification, upstream source and test PKI do not establish production custody, registration, activation or gameplay admission. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java index 835e97c749..8f708db2b2 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java @@ -231,8 +231,7 @@ Current readCurrentPublicProductionNew( } requireSupportedPublicTenantTuple( caller.snapshot(), targetTenantId, event, receipt.tenantBillingSequence()); - observed.paidSource.requireReceiptStillCurrent(receipt); - sourceValidUntilMs = receipt.validUntil().toEpochMilli(); + sourceValidUntilMs = observed.paidSource.requireReceiptStillCurrent(receipt).toEpochMilli(); } else { if (paidReceipt != null) throw unavailable(); requireCurrentDemo(caller.snapshot(), targetTenantId, selected.checkpoint()); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionPaidSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionPaidSource.java index ed68100e1d..7b6b9e63c4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionPaidSource.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionPaidSource.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.repository; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.util.Objects; import java.util.UUID; @@ -25,6 +26,7 @@ * Provider observation runs only outside SQL. This component registers no route or provider write. */ public final class AccountGameplayAdmissionPaidSource { + private static final Duration FRESHNESS_LIMIT = Duration.ofSeconds(15); private static final JsonMapper BILLING_HINT_JSON = JsonMapper.builder() .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) @@ -33,6 +35,7 @@ public final class AccountGameplayAdmissionPaidSource { private static final String BILLING_SCHEMA_VERSION = "account-hosting-subscription-event/v1"; private final AccountHostingPlanCatalog plans; private final Clock clock; + private final Duration maxClockSkew; private final ReconciliationLimits limits; private final AccountHostingSubscriptionLifecyclePolicy policy; private final StripeHostingSubscriptionObserver observer; @@ -42,6 +45,7 @@ public final class AccountGameplayAdmissionPaidSource { public AccountGameplayAdmissionPaidSource( AccountHostingPlanCatalog plans, Clock clock, + Duration maxClockSkew, ReconciliationLimits limits, AccountHostingSubscriptionLifecyclePolicy policy, StripeHostingSubscriptionObserver observer, @@ -49,6 +53,12 @@ public AccountGameplayAdmissionPaidSource( boolean livemode) { this.plans = Objects.requireNonNull(plans); this.clock = Objects.requireNonNull(clock); + if (maxClockSkew == null + || maxClockSkew.isNegative() + || maxClockSkew.compareTo(FRESHNESS_LIMIT) >= 0) { + throw new IllegalArgumentException("Entitlement clock skew must be in [0, 15 seconds)"); + } + this.maxClockSkew = maxClockSkew; this.limits = Objects.requireNonNull(limits); this.policy = Objects.requireNonNull(policy); this.observer = Objects.requireNonNull(observer); @@ -116,14 +126,19 @@ AccountHostingSubscriptionCurrentReceipt readCurrent( return receipt; } - void requireReceiptStillCurrent(AccountHostingSubscriptionCurrentReceipt receipt) { + Instant requireReceiptStillCurrent(AccountHostingSubscriptionCurrentReceipt receipt) { Instant now = clock.instant(); - if (receipt.evaluatedAt() == null - || receipt.validUntil() == null - || now.isBefore(receipt.evaluatedAt()) - || !now.isBefore(receipt.validUntil())) { + Instant evaluatedAt = receipt.evaluatedAt(); + Instant validUntil = receipt.validUntil(); + if (evaluatedAt == null || validUntil == null || evaluatedAt.isAfter(now.plus(maxClockSkew))) { + throw new IllegalStateException("Current paid NEW source has expired"); + } + Instant freshUntil = evaluatedAt.plus(FRESHNESS_LIMIT.minus(maxClockSkew)); + Instant deadline = freshUntil.isBefore(validUntil) ? freshUntil : validUntil; + if (!now.isBefore(deadline)) { throw new IllegalStateException("Current paid NEW source has expired"); } + return deadline; } private AccountHostingSubscriptionLifecycleRepository reader(DSLContext exactDsl) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index 64255954dc..bf3a90e482 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -146,6 +146,8 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.ConnectionHolder; import org.springframework.jdbc.datasource.DataSourceTransactionManager; @@ -273,7 +275,7 @@ void paidCurrentReadAndOriginalPhysicalCommitUseTheGenuineOwnerWithoutChangingSo assertThat(paid.hosting().transport().reads()).isEqualTo(reads + 1); assertThat(current.snapshot().tenantId()).isEqualTo(paid.hosting().tenantId().toString()); assertThat(current.sourceValidUntilMs()) - .isEqualTo(paid.hosting().clock().instant().plusSeconds(15).toEpochMilli()); + .isEqualTo(paid.hosting().clock().instant().plusSeconds(14).toEpochMilli()); assertThat(caller.sourceAndIssuanceImage()).isEqualTo(before); var lease = caller.beginPendingAdmissionLease(current); @@ -439,6 +441,42 @@ void paidObservationCannotRunInsideThePreparingAccountTransaction() throws Excep assertThat(paid.hosting().transport().reads()).isEqualTo(reads); } + @ParameterizedTest + @ValueSource(longs = {13_999, 14_000}) + void paidReceiptExpiresAtEntitlementDeadlineBeforeLifecycleDeadline(long elapsedMillis) + throws Exception { + PaidFixture paid = newPaidFixture(null); + Fixture caller = paid.caller(); + var observed = paid.prepare().observeOutsideSql(); + Instant evaluatedAt = paid.hosting().clock().instant(); + Instant deadline = evaluatedAt.plusSeconds(14); + Instant readTime = evaluatedAt.plusMillis(elapsedMillis); + UUID originalJti = caller.committedCandidate.identity().tokenJti(); + var reachedCallerRead = new AtomicBoolean(); + var advanceClock = + advancePaidClockDuringCallerRead(paid, originalJti, readTime, reachedCallerRead); + java.util.function.Supplier read = + () -> + caller.inCurrentSources( + sources -> + sources.readCurrentPublicProductionNew( + paid.hosting().tenantId(), + originalJti, + caller.committedCandidate, + observed), + advanceClock); + + if (readTime.isBefore(deadline)) { + assertThat(read.get().sourceValidUntilMs()).isEqualTo(deadline.toEpochMilli()); + } else { + assertThatThrownBy(read::get) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Current paid NEW source has expired"); + } + assertThat(reachedCallerRead).isTrue(); + assertThat(paid.hosting().clock().instant()).isEqualTo(readTime); + } + @Test void paidReceiptExpiringDuringFinalCallerSourceReadIsUnavailableWithoutWrites() throws Exception { PaidFixture paid = newPaidFixture(null); @@ -450,22 +488,8 @@ void paidReceiptExpiringDuringFinalCallerSourceReadIsUnavailableWithoutWrites() int providerReads = paid.hosting().transport().reads(); var before = caller.sourceAndIssuanceImage(); var reachedCallerRead = new AtomicBoolean(); - // This exact issuance SELECT is downstream of the paid receipt read and early clock check. var expireDuringCallerRead = - ExecuteListener.onExecuteEnd(ctx -> { - String sql = ctx.sql(); - var query = ctx.query(); - if (sql != null - && sql.contains( - "SELECT request_id FROM account_gameplay_delegation_issuance_operations") - && sql.contains("WHERE token_jti = ? AND status = 'COMMITTED'") - && query != null - && query.getBindValues().equals(List.of(originalJti)) - && reachedCallerRead.compareAndSet(false, true)) { - assertThat(paid.hosting().clock().instant()).isBefore(Instant.ofEpochMilli(validUntil)); - paid.hosting().clock().advanceToAtLeast(pastDeadline); - } - }); + advancePaidClockDuringCallerRead(paid, originalJti, pastDeadline, reachedCallerRead); assertThatThrownBy(() -> caller.inCurrentSources( @@ -485,6 +509,24 @@ void paidReceiptExpiringDuringFinalCallerSourceReadIsUnavailableWithoutWrites() assertThat(caller.leaseOperationCount()).isZero(); } + private static ExecuteListener advancePaidClockDuringCallerRead( + PaidFixture paid, UUID originalJti, Instant readTime, AtomicBoolean reachedCallerRead) { + // This exact issuance SELECT is downstream of the paid receipt read and early clock check. + return ExecuteListener.onExecuteEnd(ctx -> { + String sql = ctx.sql(); + var query = ctx.query(); + if (sql != null + && sql.contains("SELECT request_id FROM account_gameplay_delegation_issuance_operations") + && sql.contains("WHERE token_jti = ? AND status = 'COMMITTED'") + && query != null + && query.getBindValues().equals(List.of(originalJti)) + && reachedCallerRead.compareAndSet(false, true)) { + assertThat(paid.hosting().clock().instant()).isBefore(readTime); + paid.hosting().clock().advanceToAtLeast(readTime); + } + }); + } + @Test void paidObservationExpiryAndContradictoryProviderFactsCannotFinalizeTheOriginalLease() throws Exception { @@ -599,7 +641,7 @@ void authenticatedPaidOwnerCapsTheLeaseFinalizesOnceAndRecoversWithoutPaidAuthor .isEqualTo( Math.min( Math.min(evaluatedAt + 15_000L, identity.expiresAtEpochSecond() * 1000L), - paid.hosting().clock().instant().plusSeconds(15).toEpochMilli())); + paid.hosting().clock().instant().plusSeconds(14).toEpochMilli())); byte[] leaseBytes = lease.canonicalJson().getBytes(StandardCharsets.UTF_8); paid.hosting().providerStatus("unsupported"); var read = AccountGameplayAdmissionLeaseGrpcCodec.toReadRequest(jwt, leaseBytes); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java index c9e221e5c6..eda918ccf8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java @@ -306,7 +306,7 @@ private static Fixture createInternal( lifecycleRepository, observer, new AccountGameplayAdmissionPaidSource( - catalog, clock, limits, policy, observer, namespace, false), + catalog, clock, Duration.ofSeconds(1), limits, policy, observer, namespace, false), source); fixture.providerStatus("active"); return fixture; From f32013fa1c0c08d09c4cd129b9ef530450cd4068 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 28 Nov 2026 00:09:42 +1300 Subject: [PATCH 09/14] Use full clock precision for paid lifecycle readback --- .../AccountHostingSubscriptionLifecycleRepository.java | 5 +++-- ...rapCharacterUuidEntityCompositionIntegrationTest.java | 9 +++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java index 72fe481d6a..b4232b5753 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java @@ -1394,10 +1394,11 @@ public AccountHostingSubscriptionCurrentReceipt readCurrent( throw new FenceRejectedException( "ENTITLEMENT_UNAVAILABLE: provider facts differ from the committed receipt"); } - Instant evaluatedAt = now(); + Instant preciseEvaluatedAt = clock.instant(); + Instant evaluatedAt = preciseEvaluatedAt.truncatedTo(ChronoUnit.MICROS); var decision = retainedPolicy(operation) - .evaluate(observed, evaluatedAt, nullableInstant(receipt, "past_due_since")); + .evaluate(observed, preciseEvaluatedAt, nullableInstant(receipt, "past_due_since")); if (!decision.resolved() || !decision.status().storageValue().equals(current.status())) { throw new FenceRejectedException( "ENTITLEMENT_UNAVAILABLE: lifecycle/period requires reconciliation"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java index 384a5f4dc7..561dc1a1cd 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java @@ -453,10 +453,19 @@ void paidJoinReplayAndCharacterDiscoveryCompleteConcurrently() throws Exception String token = issuePlayerBootstrap(caller); // HTTP issuance uses the wall clock; keep the retained paid and scope fixtures on one clock. hosting.clock().advanceToAtLeast(Clock.systemUTC().instant()); + hosting + .clock() + .advanceToAtLeast( + hosting + .clock() + .instant() + .truncatedTo(java.time.temporal.ChronoUnit.MICROS) + .plusNanos(999)); var bootstrapClaims = jwtUtil.parseToken(token).getPayload(); assertThat(hosting.clock().instant()) .isAfterOrEqualTo(bootstrapClaims.getIssuedAt().toInstant()) .isBefore(bootstrapClaims.getExpiration().toInstant()); + assertThat(hosting.clock().instant().getNano() % 1_000).isEqualTo(999); String scope = discoverConnectScope(caller, token, target); var request = new JoinPublicProductionRequest(scope, UUID.randomUUID().toString()); var joined = facade.joinPublicProduction(token, request); From 93f71eba773a0c1b5d09ea266167de1a9b8a36d0 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 28 Nov 2026 05:40:07 +1300 Subject: [PATCH 10/14] Recheck paid issuance caller expiry at the commit boundary --- ...iginalNewBoundGameplayCredentialOwner.java | 3 + ...CurrentSourcesPostgresIntegrationTest.java | 1 + ...ameplayCredentialOwnerIntegrationTest.java | 56 +++++++++++++++++++ 3 files changed, 60 insertions(+) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java index 215ba9fde2..0784e83fa5 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java @@ -287,6 +287,9 @@ private IssuedOriginalNew issueChecked( new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); Genesis stored = issuance.readByLease(leaseId(requestedLease)); requireSameGenesisIdentity(exactGenesisForCommit, stored); + if (clock.instant().getEpochSecond() >= caller.identity().expiresAtEpochSecond()) { + throw unavailable(); + } Genesis committedResult = issuance.commit(stored, receiptDigest); var fenceRepository = new AccountGameplayTokenIdentityFenceRepository(dsl); var tokenIdentity = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index bf3a90e482..5f97a44943 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -435,6 +435,7 @@ void paidObservationCannotRunInsideThePreparingAccountTransaction() throws Excep paid.caller().committedCandidate.identity().tokenJti(), paid.caller().committedCandidate, paid.hosting().admissionPaidSource()); + assertThat(prepared).isNotNull(); assertThatThrownBy(prepared::observeOutsideSql).isInstanceOf(IllegalStateException.class); return null; }); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java index defbde11e0..eb0ccdfa35 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java @@ -149,6 +149,14 @@ void paidConfirmationWithElapsedContinuityDoesNotWriteReadback() throws Exceptio exerciseFinalConfirmation(false, false, true); } + @Test + void paidIssuanceWithCallerExpiringDuringCommitObservationLeavesGenesisPending() + throws Exception { + paidFixture = fixtureHarness.newPaidFixture(redisFixture.client()); + sourceFixture = paidFixture.caller(); + exerciseFinalConfirmation(false, false, false, true); + } + private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) throws Exception { exerciseFinalConfirmation(revokeCallerDuringFinalRead, false); } @@ -165,6 +173,19 @@ private void exerciseFinalConfirmation( boolean changePaidSourceDuringObservation, boolean expireContinuityDuringConfirmationObservation) throws Exception { + exerciseFinalConfirmation( + revokeCallerDuringFinalRead, + changePaidSourceDuringObservation, + expireContinuityDuringConfirmationObservation, + false); + } + + private void exerciseFinalConfirmation( + boolean revokeCallerDuringFinalRead, + boolean changePaidSourceDuringObservation, + boolean expireContinuityDuringConfirmationObservation, + boolean expireCallerDuringIssuanceObservation) + throws Exception { AtomicReference selectedOwnerClock = new AtomicReference<>(Clock.systemUTC()); Clock ownerClock = new Clock() { @@ -350,6 +371,41 @@ public Instant instant() { return; } + if (expireCallerDuringIssuanceObservation) { + var issuances = DSL.table("account_original_new_bound_gameplay_issuances"); + var committedIssuances = DSL.field("status", String.class).eq("COMMITTED"); + var identityFences = DSL.table("account_gameplay_token_identity_fences"); + int committedCount = dsl.fetchCount(issuances, committedIssuances); + int fenceCount = dsl.fetchCount(identityFences); + var transport = paidFixture.hosting().transport(); + int before = transport.reads(); + Instant callerExpiry = Instant.ofEpochSecond(initialIdentity.expiresAtEpochSecond()); + // Let the initial source read and signed-candidate binding finish before advancing time. + transport.duringRead(() -> + transport.duringRead(() -> + transport.duringRead( + () -> selectedOwnerClock.set(Clock.fixed(callerExpiry, ZoneId.of("UTC")))))); + + assertThatThrownBy(() -> + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .call(() -> owner.issue(loginJwt, originalLease))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Original-new bound gameplay credential is unavailable"); + assertPaidObservationReadsSince(before, 3); + assertThat(ownerClock.instant()).isEqualTo(callerExpiry); + assertThat(dsl.fetchCount(issuances, committedIssuances)).isEqualTo(committedCount); + assertThat(dsl.fetchCount(identityFences)).isEqualTo(fenceCount); + Genesis pending = readGenesis(dsl, serializable, originalLease); + assertThat(pending.status()) + .isEqualTo(AccountOriginalNewBoundGameplayIssuanceRepository.Status.PENDING); + assertThat(pending.tokenHash()).isNotNull(); + assertThat(pending.committedRegistryReceiptSha256()).isNull(); + assertThat(finalReadCalls.get()).isZero(); + assertOriginalLeaseAndAckRemainExact(dsl, originalLease, originalEvidenceSha256); + return; + } + OriginalNewCredential first = Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) From fdc3ef0e04f73811b64aa6c7c6520598171dbccf Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 28 Nov 2026 05:49:51 +1300 Subject: [PATCH 11/14] Read final admission target after the paid observation --- .../AccountGameplayAdmissionLeaseOwner.java | 14 ++++++------- ...CurrentSourcesPostgresIntegrationTest.java | 21 +++++++++++++++++++ 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwner.java index acdb833230..26bfb9539e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwner.java @@ -218,15 +218,14 @@ public AccountGameplayAdmissionLeaseResponse finalizeLease( null); } - // Both remote authorities are read after the short Account replay lookup and before the - // original physical-COMMIT path. The decision reader returns only the actual retained - // lease-bound PROVISIONAL decision, never request echoes. - Evidence decision; - PublishedRealmEvidence published; + // Complete the paid observation outside SQL before reading either Game Session authority. + // The decision or published target can change while the provider read is in flight. + AccountGameplayAdmissionCurrentSources.Observed observed; try { - decision = decisionReadClient.read(request.bindingDecisionId(), lease); + observed = prepareCurrentSources(caller, tenantId(lease)); + Evidence decision = decisionReadClient.read(request.bindingDecisionId(), lease); requireDecisionMatchesLease(decision, request.bindingDecisionId(), lease, caller, peer); - published = + PublishedRealmEvidence published = readPublishedTarget(requestId(lease), decision.candidate(), decision.targetEvidence()); if (!published.currentTarget().equals(decision.targetEvidence())) throw unavailable(); } catch (RuntimeException unavailable) { @@ -261,7 +260,6 @@ public AccountGameplayAdmissionLeaseResponse finalizeLease( // through this executor to reconstruct a late acknowledgement. OriginalCommitAcknowledgement acknowledgement; try { - var observed = prepareCurrentSources(caller, tenantId(lease)); acknowledgement = originalCommitExecutor.executeWithCurrentSources( lease, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index 5f97a44943..8baa175393 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -663,6 +663,27 @@ void authenticatedPaidOwnerCapsTheLeaseFinalizesOnceAndRecoversWithoutPaidAuthor .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.PENDING); paid.hosting().providerStatus("active"); + var publishedTarget = controlledPublishedTarget(candidate, target, requestId); + var targetWithdrawn = new AtomicBoolean(); + when(decisions.readPublishedRealmAdmissionOwner(any())) + .thenAnswer(invocation -> { + if (targetWithdrawn.get()) throw Status.UNAVAILABLE.asRuntimeException(); + return publishedTarget; + }); + paid.hosting().transport().duringRead(() -> targetWithdrawn.set(true)); + assertThatThrownBy(() -> withPeer(peer, () -> owner.finalizeLease(finalize))) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(targetWithdrawn.get()).isTrue(); + var stillPending = caller.readLeaseOperation(lease); + assertThat(stillPending.state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.PENDING); + assertThat(stillPending.evidence().canonicalJson()).isEqualTo(lease.canonicalJson()); + assertThat(caller.originalAckReceiptImage(requestId)).isEmpty(); + + targetWithdrawn.set(false); withPeer(peer, () -> response.set(owner.finalizeLease(finalize))); var committed = response.get(); assertThat( From 8d84cba3d8e22251519751e3a1a3a6fe4b9946de Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 28 Nov 2026 06:03:56 +1300 Subject: [PATCH 12/14] Fence paid Redis activation with current Account source evidence --- ...untOriginalNewBoundGameplayCredentialOwner.java | 14 ++++++++++---- ...oundGameplayCredentialOwnerIntegrationTest.java | 14 +++++++++++--- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java index 0784e83fa5..55cc5fb5a5 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java @@ -502,7 +502,7 @@ dsl, new AccountGameplayAdmissionLeaseRepository(dsl)) throw unavailable(); } - if (committedCapacityRequest != null) { + if (committedCapacityRequest != null || beforeRead.paidHosting()) { AccountGameplayAdmissionCurrentSources.Observed beforeActivationObservation = prepareCurrentOriginalSource(beforeActivationCaller, requestedLease); inWritableSerializableTransaction(dsl -> { @@ -510,7 +510,8 @@ dsl, new AccountGameplayAdmissionLeaseRepository(dsl)) readCurrentOriginalSource( dsl, beforeActivationCaller, requestedLease, beforeActivationObservation); requireSameOriginalOperation(beforeRead.operation(), current.operation()); - return readCommittedCapacity(dsl, current.operation(), peer, committedCapacityRequest); + readCommittedCapacity(dsl, current.operation(), peer, committedCapacityRequest); + return current; }); if (Context.current().isCancelled()) throw unavailable(); } @@ -927,7 +928,10 @@ private SourceRead readCurrentOriginalSource( new AccountGameplayAdmissionLeaseRepository(dsl) .readExact(lease) .orElseThrow(AccountOriginalNewBoundGameplayCredentialOwner::unavailable); - return new SourceRead(operation, current.currentCommittedCandidate().authoritySnapshot()); + return new SourceRead( + operation, + current.currentCommittedCandidate().authoritySnapshot(), + current.sourceValidUntilMs() != null); } private Binding responseBinding( @@ -1269,7 +1273,9 @@ private static IllegalStateException unavailable() { } private record SourceRead( - AccountGameplayAdmissionLeaseOperation operation, AccountAuthoritySnapshot accountAuthority) { + AccountGameplayAdmissionLeaseOperation operation, + AccountAuthoritySnapshot accountAuthority, + boolean paidHosting) { SourceRead { Objects.requireNonNull(operation); Objects.requireNonNull(accountAuthority); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java index eb0ccdfa35..3d12eec740 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java @@ -143,7 +143,7 @@ void paidSourceHeadChangeDuringObservationRefusesOriginalCredentialIssuance() th } @Test - void paidConfirmationWithElapsedContinuityDoesNotWriteReadback() throws Exception { + void paidConfirmationWithElapsedContinuityLeavesRegistryPending() throws Exception { paidFixture = fixtureHarness.newPaidFixture(redisFixture.client()); sourceFixture = paidFixture.caller(); exerciseFinalConfirmation(false, false, true); @@ -494,6 +494,14 @@ public Instant instant() { assertThat(finalReadCalls.get()).isOne(); assertThat(continuityAdvances.get()).isOne(); assertUnconfirmed(dsl, serializable, originalLease); + byte[] expectedPending = committed.pendingRegistryRecordBytes(); + try { + redisFixture + .client() + .requirePendingRecord(committed.tokenHash(), expectedPending, exactRedisExpiryMillis); + } finally { + Arrays.fill(expectedPending, (byte) 0); + } assertThat(issuancePhysicalImage(dsl)).isEqualTo(before); assertOriginalLeaseAndAckRemainExact(dsl, originalLease, originalEvidenceSha256); return; @@ -629,8 +637,8 @@ public Instant instant() { finalReadMode.set(FinalReadMode.EXACT); int paidReadsBeforeExactFinal = paidObservationReads(); var confirmed = confirm(owner, peer, loginJwt, originalLease); - // Early source, genesis, a single frozen-credential open, and final confirmation. - assertPaidObservationReadsSince(paidReadsBeforeExactFinal, 4); + // Early source, genesis, frozen-credential open, preactivation, and final confirmation. + assertPaidObservationReadsSince(paidReadsBeforeExactFinal, 5); assertThat(confirmed.lineageId()).isEqualTo(first.lineageId()); assertThat(confirmed.originalLeaseId()) .isEqualTo(UUID.fromString((String) originalLease.carrier().get("leaseId"))); From 722d892a174858ccefa729f95f9e23b1efe0d8e7 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 28 Nov 2026 06:30:29 +1300 Subject: [PATCH 13/14] Replay retained JOIN denials without waiting on the payer --- .../service/impl/AccountServiceImpl.java | 30 +++++++++++++++---- .../service/impl/AccountServiceImplTest.java | 10 ++++++- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 1b40360ca3..d34fa114c0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -595,10 +595,21 @@ private CanonicalJoinPreparation prepareCanonicalJoin( String requestId, String callerBinding) { // Retain the exact policy-independent intent before any fallible source/provider work. - joinTransactionTemplate.executeWithoutResult(status -> { - lockCanonicalScopeAccount(scope); - accountJoinOperationRepository.insertCanonicalIntent(requestId, scope, callerBinding); - }); + var retainedFailure = + Objects.requireNonNull( + joinTransactionTemplate.execute(status -> { + lockCanonicalScopeAccount(scope); + if (accountJoinOperationRepository.insertCanonicalIntent( + requestId, scope, callerBinding)) { + return Optional.empty(); + } + return accountJoinOperationRepository + .findCanonicalEvidenceByRequestId(requestId) + .filter(operation -> "FAILED".equals(operation.status())); + })); + if (retainedFailure.isPresent()) { + return new CanonicalJoinPreparation(retainedFailure.orElseThrow(), null, null, null); + } return Objects.requireNonNull( joinTransactionTemplate.execute(status -> { // Lock the caller and distinct payer before source selection or a hosting read. @@ -636,8 +647,11 @@ private CanonicalJoinResult commitCanonicalJoin( StripeHostingSubscriptionObserver.Result observation) { return Objects.requireNonNull( joinTransactionTemplate.execute(status -> { - // The provider observation was outside SQL; reacquire the same Account lock order. - accountRepository.lockCanonicalJoinAccounts(scope.tenantId(), scope.accountId()); + boolean retainedFailure = "FAILED".equals(prepared.operation().status()); + // Only source-dependent work needs the sorted caller and payer locks. + if (!retainedFailure) { + accountRepository.lockCanonicalJoinAccounts(scope.tenantId(), scope.accountId()); + } lockCanonicalScopeAccount(scope); requireCanonicalScopeFresh(consumers, scope); CanonicalJoinOperationEvidence lockedOperation = @@ -652,6 +666,10 @@ private CanonicalJoinResult commitCanonicalJoin( requestId, scope, callerBinding, lockedOperation.outcome()); return new CanonicalJoinResult(retained.outcome(), null, false, true); } + if (retainedFailure) { + throw new AccountJoinOperationRepository.CanonicalJoinOperationConflictException( + "Retained JOIN failure changed before replay"); + } SourceSelection current = consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); if (current.kind() != prepared.source().kind() diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 5f88336359..717ddedd45 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -1122,6 +1122,8 @@ void canonicalFailedRetryPreservesTheOriginalOutcomeWithoutMembershipOrPolicyMut String outcome) { var f = canonicalJoinFixture(); when(f.pending.status()).thenReturn("FAILED"); + when(accountJoinOperationRepository.findCanonicalEvidenceByRequestId(f.requestId)) + .thenReturn(Optional.of(f.pending)); when(f.pending.outcome()).thenReturn(outcome); when(accountJoinOperationRepository.finishCanonicalFailure( f.requestId, f.scope, f.binding, outcome)) @@ -1134,6 +1136,8 @@ void canonicalFailedRetryPreservesTheOriginalOutcomeWithoutMembershipOrPolicyMut assertTrue(result.replayed()); assertEquals(outcome, result.outcomeCode()); verifyNoInteractions(f.targets, f.sources, f.demos, f.hosting, f.observer, f.terminal); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .lockCanonicalJoinAccounts(f.scope.tenantId(), f.scope.accountId()); org.mockito.Mockito.verify(accountJoinOperationRepository) .finishCanonicalFailure(f.requestId, f.scope, f.binding, outcome); org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.times(2)) @@ -1144,6 +1148,8 @@ void canonicalFailedRetryPreservesTheOriginalOutcomeWithoutMembershipOrPolicyMut void canonicalFailedRetryStillChecksLockedRequestIdentity() { var f = canonicalJoinFixture(); when(f.pending.status()).thenReturn("FAILED"); + when(accountJoinOperationRepository.findCanonicalEvidenceByRequestId(f.requestId)) + .thenReturn(Optional.of(f.pending)); when(f.pending.outcome()).thenReturn("PUBLIC_PRODUCTION_ADMISSION_DENIED"); when(accountJoinOperationRepository.finishCanonicalFailure( f.requestId, f.scope, f.binding, "PUBLIC_PRODUCTION_ADMISSION_DENIED")) @@ -1153,7 +1159,7 @@ void canonicalFailedRetryStillChecksLockedRequestIdentity() { assertEquals( "IDEMPOTENCY_CONFLICT", assertThrows(AuthenticationException.class, f::browserJoin).getCode()); - org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(2)) + org.mockito.Mockito.verify(accountJoinOperationRepository) .findCanonicalEvidenceForUpdateByRequestId(f.requestId); verifyNoInteractions(f.targets, f.sources, f.demos, f.hosting, f.observer, f.terminal); } @@ -1162,6 +1168,8 @@ void canonicalFailedRetryStillChecksLockedRequestIdentity() { void canonicalFailedRetryStillRechecksCallerBeforeLockedReplay() { var f = canonicalJoinFixture(); when(f.pending.status()).thenReturn("FAILED"); + when(accountJoinOperationRepository.findCanonicalEvidenceByRequestId(f.requestId)) + .thenReturn(Optional.of(f.pending)); when(sessionService.isAccountSessionActive(f.account.getId(), f.bootstrap)) .thenReturn(true, false); assertEquals( From 3b85e1010c7f360dd9febd7647e721cc1192b587 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 28 Nov 2026 08:28:57 +1300 Subject: [PATCH 14/14] Bound original NEW credential issuance by the admission deadline --- .../AccountGameplayAdmissionLeaseClient.java | 27 ++++++++++++------- ...yOriginalNewFinalAdmissionCoordinator.java | 8 +++--- ...countGameplayAdmissionLeaseClientTest.java | 14 +++++----- 3 files changed, 29 insertions(+), 20 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClient.java index 87a34808f1..9d3862860e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClient.java @@ -240,6 +240,14 @@ public OperationEvidence abort( */ public OriginalNewCredential issueOriginalNewBoundGameplayCredential( String presentedInitialGsACompactJwt, byte[] originalLeaseEvidenceUtf8) { + return issueOriginalNewBoundGameplayCredential( + presentedInitialGsACompactJwt, originalLeaseEvidenceUtf8, null); + } + + public OriginalNewCredential issueOriginalNewBoundGameplayCredential( + String presentedInitialGsACompactJwt, + byte[] originalLeaseEvidenceUtf8, + Deadline operationDeadline) { requireNoAmbientSql("Original-new credential issuance requires no ambient SQL"); var wireRequest = AccountGameplayAdmissionLeaseGrpcCodec.toIssueOriginalNewCredentialRequest( @@ -252,7 +260,7 @@ public OriginalNewCredential issueOriginalNewBoundGameplayCredential( AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialResponse( expected, requireInitializedStub("Account lease service is not initialized") - .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .withDeadline(boundedAdmissionDeadline(operationDeadline)) .issueOriginalNewGameplayCredential(wireRequest)); if (!credential .originalLeaseId() @@ -308,15 +316,9 @@ public OriginalFinalAdmissionConfirmation confirmOriginalNewGameplayAdmission( expected, withPublishedInitializedStub( "Account lease service is not initialized", - stub -> { - var bounded = - operationDeadline == null - ? stub.withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) - : stub.withDeadline( - operationDeadline.minimum( - Deadline.after(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS))); - return bounded.confirmOriginalNewGameplayAdmission(wireRequest); - })); + stub -> + stub.withDeadline(boundedAdmissionDeadline(operationDeadline)) + .confirmOriginalNewGameplayAdmission(wireRequest))); } catch (StatusRuntimeException failure) { throw statusFailure("Account original-new admission confirmation failed", failure); } catch (IllegalArgumentException malformed) { @@ -336,6 +338,11 @@ private void requireLeaseCorrelation(AccountGameplayAdmissionLeaseEvidence lease } } + private static Deadline boundedAdmissionDeadline(Deadline operationDeadline) { + Deadline rpcDeadline = Deadline.after(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); + return operationDeadline == null ? rpcDeadline : operationDeadline.minimum(rpcDeadline); + } + private static IllegalStateException statusFailure( String message, StatusRuntimeException failure) { StatusRuntimeException sanitizedStatus = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java index f62d41c9f1..9e2f3275c9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java @@ -145,7 +145,7 @@ FinalAdmissionResult completeOriginalNew( accountClient.confirmOriginalNewGameplayAdmission( originalLoginJwt, originalLeaseBytes, - confirmationDeadline(absoluteDeadlineMillis), + admissionDeadline(absoluteDeadlineMillis), committedCapacity.selector()); requireDeadline(absoluteDeadlineMillis); requireConfirmation(source, recoveredConfirmation, null, originalDecision); @@ -157,7 +157,7 @@ FinalAdmissionResult completeOriginalNew( try (OriginalNewCredential credential = accountClient.issueOriginalNewBoundGameplayCredential( - originalLoginJwt, originalLeaseBytes)) { + originalLoginJwt, originalLeaseBytes, admissionDeadline(absoluteDeadlineMillis))) { requireCredentialLease(source, originalDecision, credential); try (CanonicalGameplayOriginalNewAuthenticatedSession.Template template = CanonicalGameplayOriginalNewAuthenticatedSession.template( @@ -288,7 +288,7 @@ FinalAdmissionResult completeOriginalNew( accountClient.confirmOriginalNewGameplayAdmission( originalLoginJwt, originalLeaseBytes, - confirmationDeadline(absoluteDeadlineMillis), + admissionDeadline(absoluteDeadlineMillis), committedCapacity == null ? null : committedCapacity.selector()); requireDeadline(absoluteDeadlineMillis); requireConfirmation(source, confirmation, credential, originalDecision); @@ -669,7 +669,7 @@ private void requireCurrentOpenWindow( } } - private Deadline confirmationDeadline(long absoluteDeadlineMillis) { + private Deadline admissionDeadline(long absoluteDeadlineMillis) { long remainingMillis = Math.subtractExact(absoluteDeadlineMillis, clock.millis()); if (remainingMillis <= 0L) throw unavailable(); return Deadline.after(remainingMillis, TimeUnit.MILLISECONDS); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java index 9ae4088323..1e31c093a0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java @@ -323,7 +323,8 @@ public void confirmOriginalNewGameplayAdmission( client.init(); byte[] originalLease = lease().canonicalJson().getBytes(StandardCharsets.UTF_8); OriginalNewCredential received = - client.issueOriginalNewBoundGameplayCredential(JWT, originalLease); + client.issueOriginalNewBoundGameplayCredential( + JWT, originalLease, Deadline.after(3, TimeUnit.SECONDS)); byte[] receivedHandle = received.opaqueRebindHandle(); try { assertThat(receivedHandle).containsExactly(handle); @@ -358,11 +359,12 @@ public void confirmOriginalNewGameplayAdmission( .containsExactly(originalLease); }); assertThat(deadlines).hasSize(3); - assertThat(deadlines.subList(0, 2)) - .allSatisfy(deadline -> { - long remainingMillis = deadline.timeRemaining(TimeUnit.MILLISECONDS); - assertThat(remainingMillis).isPositive().isLessThanOrEqualTo(5_000L); - }); + assertThat(deadlines.get(0).timeRemaining(TimeUnit.MILLISECONDS)) + .isPositive() + .isLessThanOrEqualTo(3_000L); + assertThat(deadlines.get(1).timeRemaining(TimeUnit.MILLISECONDS)) + .isPositive() + .isLessThanOrEqualTo(5_000L); assertThat(deadlines.get(2).timeRemaining(TimeUnit.MILLISECONDS)) .isPositive() .isLessThanOrEqualTo(3_000L);