diff --git a/design/architecture/microservices/account-service/stripe-integration.md b/design/architecture/microservices/account-service/stripe-integration.md index 48b11f8140..cbb4a55e3d 100644 --- a/design/architecture/microservices/account-service/stripe-integration.md +++ b/design/architecture/microservices/account-service/stripe-integration.md @@ -166,6 +166,10 @@ Subscription creation, lifecycle, and entitlements are covered in more detail in 6. Stripe webhooks caused by initial provisioning or an explicit existing-subscription update resolve through the exact typed `subscription_provisioning` or `subscription_update` operation identity carried in provider metadata. Provider-lifecycle events such as subscription status or invoice events that do not originate from a current command use a separate `subscription_lifecycle` correlation: Account verifies the signature, deduplicates by Stripe `event.id` in `stripe_event_inbox`, resolves the provider subscription ID from the event payload to the unique canonical subscription and its immutable internal `subscriptionId`, and does not fabricate or reuse a command operation identity. If the provider ID is not yet linked or the local row cannot be resolved, the inbox correlation remains durably `pending` with retry state; reconciliation looks up current provider state, repairs the provider-ID/local-row linkage, and then applies a guarded transition. Replayed events are no-ops after durable deduplication, while out-of-order or ambiguous lifecycle events remain pending for reconciliation rather than regressing local state. Both command and lifecycle paths keep the internal `subscription` table in sync. 7. Changes to `subscription.status` are propagated to tenant-management and quota-enforcement components so that tenant availability and resource limits reflect the current billing state. For hard cutoff transitions such as `suspended` or `canceled`, Account transactionally advances the durable tenant authority generation with the committed billing state and emits `SubscriptionStatusChanged` plus `TenantBillingStateChanged`. Downstream services consume those events to invalidate projections and terminate affected gameplay sessions; they never advance Account authority themselves. See [Subscription Management](./subscription-management.md#tenant-availability-and-quota-enforcement) and [Session Behavior](../../system-architecture-session-behavior.md#session-and-identity-management). +#### Investigating an ambiguous first dispatch + +For a `subscription_provisioning_operator_outbox` item with `STALLED_WITHOUT_COMMITTED_PROGRESS` or `ABSOLUTE_DEADLINE`, correlate the original request and subscription IDs with the immutable provider dispatch claim. A `FIRST_DISPATCH` claim records that one invocation obtained permission, which it can lose before sending the create. If the provider subscription ID is absent, a lost response and an unsent request remain indistinguishable from the claim alone. Check the original provisioning metadata and exact customer binding through the authorized read-only reconciliation path. Empty search or list results leave the outcome unresolved. Retain the reservation and operator item until the existing guarded reconciliation or terminal cleanup can establish its required evidence. The claim and outbox item confer no permission to issue another create. + ## Multi-Tenancy and Security Stripe integration must preserve tenant isolation while allowing platform-level reporting: 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 67eb8aee7d..5ff84ebab3 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -24,7 +24,7 @@ This is an intentionally breaking preproduction format cutover of the manually c ### Canonical receiving capability boundaries -The Account source/transport foundation contains unregistered TENANT_OPERATION and PLAYER_ADMISSION owners, transports and controlled proof, Entity persisted-actor discovery, and policy-aware Game Session discovery. These do not replace live PLAY authority. The public receiving boundary contains canonical UUID schema retirement, the public facade/JOIN cutover, the schema/retention foundation and focused owner units. Provider-write execution, expanded physical proof and private FRESH/World preparation remain separate receiving obligations. A functioning canonical PLAY replacement remains unqualified; no caller custody, runtime registration, admission or activation is established by these source boundaries. +The Account source/transport foundation contains unregistered TENANT_OPERATION and PLAYER_ADMISSION owners, transports and controlled proof, Entity persisted-actor discovery, and policy-aware Game Session discovery. These do not replace live PLAY authority. The public receiving boundary contains canonical UUID schema retirement, the public facade/JOIN cutover, initial hosting provider-write source with its focused units, and dependent physical proof. Private FRESH/World preparation remains a separate receiving obligation. A functioning canonical PLAY replacement remains unqualified; no caller custody, runtime registration, admission or activation is established by these source boundaries. ### Controlled player-admission transport composition @@ -34,15 +34,29 @@ A further prepared [committed-LOGIN composition](../../../services/account-servi ### Canonical billing and retention receiving -This Account cutover retains the original numeric subscription heap as immutable, non-authorizing history (V1028), installs the canonical UUID subscription intent/provider-history, provisioning, first-dispatch, terminal-resolution and wallet-settlement schema (V1029/V1030/V1032/V1036/V1039), and moves retention/deletion reads to the dedicated historical-evidence repository. The old numeric entitlement reader and demo subscription seeder are removed together. Numeric runtime entitlement requests fail closed; no canonical entitlement is inferred from retained rows. +The receiving foundation retains numeric subscription rows in the original renamed heap as immutable, non-authorizing evidence (V1028), installs canonical UUID subscription intent/provider history (V1029), and retains complete provisioning/lifecycle schema (V1030), first-dispatch claims (V1032) and cancellation-resolution journals (V1036). Retained history remains useful only for conservative deletion blockers; it is never current entitlement authority. The manually composed cancellation component keeps actual Account actor/authentication and owner-local atomic receipt/fence/event checks and prepares one allowed safe outcome. Historical coupled 356 physical proof passed through genuine certified ACCOUNT issuance/current actor, fresh primary OTP authentication and the guarded cancellation commit; the later exact-head failures and replacement-proof limits below qualify that retained history. The five PostgreSQL/AOF-replica cases recorded at `f5fd19cd79` cover atomic row/CAS/journal/receipt/audit/billing/tenant-event completion, canonical canceled current-read recovery, immutable failed history, authenticated replay, wrong credentials, late SQL rollback with restored OTP, authority change during the SDK read, and another Account's credential refusal. Enabled integration/test-fixture analysis and formatting pass. Unchanged 355 regression passes 20 lifecycle and 21 original-order cases; its original aggregate retains the corrected error-code expectation failure. These qualify the prepared cancellation component, with controlled policy/signer and Stripe transport inputs, and do not establish production custody or runtime registration. Provider absence and transfer are separate outcomes; production/default registration remains held and is not a prerequisite to qualifying this unregistered component boundary. -The immediate successor owns the initial Stripe provider-write adapter and provisioning composition, the unclaimed-wallet settlement repository refinements, their focused unit and native PostgreSQL proof, and expanded World/stub receiving compositions. Those source and proof obligations are preserved in the original #3390 history and the complete successor tree. Their earlier source-specific proof is not proof of this reduced parent. Required physical migration, fresh-image runtime and exact-head CI qualification remain separate from local source compilation and focused units. +The current [terminal cancellation composition](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java) contains six cases. The additional `missingFailedOperationCopyRejectsBeforeCurrentCasAndRollsBackAuditJournalAndOtp` case was added later at `71e634aede` and is not covered by the historical coupled 356 five-case result. The current fixture's recorded compilation does not establish physical execution of that additional case; separate physical proof remains outstanding. -Account deletion remains held. Its conservative billing-owner precondition inspects retained numeric history, not nonterminal canonical UUID subscriptions. No provider worker, billing mutation route, player admission or production activation is enabled by this split. +The physical Account partitions from run `42329363290` at merge `db84cabe83ab93dc0aac28f359a3f359cd52bfd6` for published `3adbf512` expose four stale assertions; their failures remain retained. The corrected [lifecycle fixture](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java) separates an unresolved first `past_due` observation without retained episode origin from effective cancellation starting at a valid active receipt. The unresolved case requires `RECONCILING` / `RECOVERY_ORIGIN_UNRESOLVED`, unchanged prior receipt and authority, no new positive event and a held instrument reservation. Genuine `past_due` → `grace` → `suspended` physical coverage still requires an authoritative retained episode origin and is not established by this correction; Account owns that positive proof obligation before recovery-lifecycle qualification. The independent cancellation case retains monotonic cutoff, replacement refusal and reservation release only after confirmed provider cancellation. The [currentness fixture](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java) uses a supported `active` → `canceled` transition to preserve checkpoint, replay, monotonic authority/event, realm-grant tombstone and direct-SQL reactivation-refusal assertions without claiming `past_due` coverage. The [dispatch fixture](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java) now expects the earlier typed original-binding fence after replacement, with unchanged durable row images and no provider create. The [terminal composition fixture](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java) now expects typed source unavailability after a real generic Account authority/fence advance, preserving unchanged financial/failure evidence and an unconsumed OTP; that generic event does not prove a supported current-actor mismatch branch. Production policy, fence ordering and closed source-event families remain unchanged. The reconstructed source and these four corrections pass affected Account production/unit/integration compilation, enabled Account static analysis, World cross-service compilation, Java formatting and documentation checks. The same locked local gate passed all 39 focused Game Session discovery cases and 18 codec cases in 7m26s. The four PostgreSQL corrections were compiled, not executed locally; replacement physical proof remains outstanding and no runtime Smoke pass is claimed for this unfinished cutover. + +Account deletion remains held. Its conservative billing-owner precondition currently inspects only retained numeric subscription history; it does not yet read nonterminal canonical UUID subscriptions owned by the Account. After the earlier retained-JOIN blocker is clear, a canonical-only billing owner therefore receives `ACCOUNT_DELETE_UNAVAILABLE`, not the required `ACCOUNT_DELETE_ACTIVE_BILLING_OWNER`. The deletion owner must qualify that canonical current-owner check and positive/negative proof before deletion can be enabled, while preserving retained-history blockers and the [Account deletion contract](../../architecture/microservices/account-service/api-contracts.md). No deletion or billing-owner release is enabled by this foundation. + +This receiver owns the [Stripe provisioner](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java), [provisioning composition](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java), their [adapter units](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java) and [composition units](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java), and the existing [dispatch physical suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java). Beyond moving the inherited source/unit files from #3389, the receiver adds local settlement for undispatchable work. A later wallet observation still rejects provider dispatch against the exact reserved instrument version, but the retained claim can move to `RECONCILING` and then terminal operator work at its deadline without releasing the reservation or inferring provider absence. A changed instrument before the initial claim instead retains unclaimed terminal work with `RESERVED_INSTRUMENT_CHANGED`, without issuing a claim or dispatch. + +Focused source coverage includes `refusedDispatchCommitsLocalDeferralWithoutCallingProvider` and `refusedDispatchCannotHideStaleClaimSettlementFailure` in the composition units, and `displayRefreshAfterClaimRefusesDispatchButRetainedWorkReachesOperatorDeadline`, `displayRefreshAfterDispatchPreparationRefusesReadbackAndStillAllowsLocalDeadlineFailure`, and `displayRefreshBeforeInitialClaimRetainsTerminalFailureWithoutDispatch` in the dispatch physical suite. These changes do not establish new payment support or completed physical qualification; the execution limits above remain, and both components stay manually composed and unregistered, with the authenticated create producer, provider worker and public billing route held. + +The paid first-invoice confirmation finding remains open in this receiving boundary. Stripe `default_incomplete` creation and subscription polling do not confirm a required first payment. The dispatch physical suite models an incomplete create, checks that no active receipt commits, and supplies a controlled confirmation before the same lifecycle operation can commit. Live confirmation still belongs to the accepted Account/provider-hosted checkout boundary after confirmed provider linkage, preserving [ADR 0044](../../architecture/decisions/adr-0044-account-owned-payment-instruments-with-explicit-subscription-binding.md) and [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); do not enable automatic charging inside the held provisioning adapter. Runtime registration and activation remain held. + +The current billing-owner tuple deliberately rejects unaudited updates. Fixture reconciliation preserves that refusal and unchanged row/xmin, stale owner version/generation capture refusal, and genuine payment-instrument advancement concurrency. Positive queued-create fencing after a real audited owner-transfer commit remains an obligation of the unimplemented transfer owner; constructed stale comparison inputs do not prove that transfer. + +The same receiving boundary carries the distinct TENANT_OPERATION evidence, Account source/peer-qualified receiver, and World client/mTLS proof. These are unregistered source components, with controlled upstream/PKI limitations. Receiving compilation 328 passes. Focused 331 executes 203 Account units, nine shared evidence/transport cases, four actual World→Account mTLS cases and 80 PostgreSQL cases; its aggregate fails two intent fixtures. Corrected 336 passes all 20 intent cases (including the additional unaudited-update refusal), enabled affected static checks, formatting and documentation. Together these executions establish 81 unique focused PostgreSQL cases without failures/errors/skips; unchanged passing suites retain 331 attribution. Fresh-image/runtime and current-head CI/review remain required; controlled sources/PKI do not establish production custody or authenticated transfer. + +The earlier published #3389 comparison deliberately left public facade and numeric runtime entitlement paths unavailable; its historical source-built340 run passed held-edge denial and LOGIN but failed PLAY with ENTITLEMENT_UNAVAILABLE. Authenticated teardown and independently empty resources passed. This remains incomplete runtime qualification for that historical comparison, not a passing smoke result or a description of the reconstructed #3389 foundation, which preserves the supported parent runtime. The complete public consumer receiving below restores its own supported canonical compositions; canonical runtime cutover and final functional restoration remain separate obligations. Ordinary UUID identity/profile/retention protections retain their focused proof. ### Canonical public Account facade receiving -The parent source restores the complete canonical V2 public facade, actual Account JOIN intent/member/pair/role/event/audit owners, V1037 diagnostics and V1038 existing-membership terminal guard, plus the distinct PLAYER_ADMISSION codec/Account receiver/Game Session client and persisted Account→Entity CHARS purpose. It retains actual same-row actor UUID/name/level, successful empty discovery only for supported targets, truthful admission flags, default-unavailable composition and all original positive cases. Contracts belong to [Account API](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery). +The receiving source now restores the complete canonical V2 public facade, actual Account JOIN intent/member/pair/role/event/audit owners, V1037 diagnostics and V1038 existing-membership terminal guard, plus the distinct PLAYER_ADMISSION codec/Account receiver/Game Session client and persisted Account→Entity CHARS purpose. It retains actual same-row actor UUID/name/level, successful empty discovery only for supported targets, truthful admission flags, default-unavailable composition and all original positive cases. Contracts belong to [Account API](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery). Preserved source proof 310 passes 575 selected Account units; proof 318 passes 312 facade units and two actual HTTP→Entity compositions; proof 320 passes 42 App PostgreSQL cases; proof 321 passes 13 first-JOIN cases; proof 324 passes 22 PLAYER_ADMISSION owner cases plus five shared cases; and proof 335 passes three actual PLAYER_ADMISSION PostgreSQL cases. These are source-specific executions with controlled upstream/PKI limits. Actual receiving compilation 342 passes all affected production/unit/integration sources after carrying the complete transport closure. Receiving proofs 343/345 establish 793 unique selected unit passes after correcting one obsolete first-only generic proof assertion; proof 351 passes 169 selected physical PostgreSQL/HTTP/mTLS/composition cases across Account, Entity, Game Session and World without failures, errors or skips, including both canonical HTTP-to-Entity positives deferred from the foundation. Enabled affected static checks pass except CommonCore SpotBugsTest in proof 346, whose JVM SIGSEGV leaves that task held and the aggregate failed; existing Game Session main proof 198/200 holds remain. Remaining proof 347 static and documentation checks pass. These focused results do not establish complete service suites or runtime qualification. The explicit Game Session entitlement client also prepares a canonical direct-text lobby-scope input under its owning current-custody callback, preserving original LOGIN/transport/target/expiry bindings without a fabricated first-party context. Focused transport proof 352 passes all 34 mTLS client cases (31 new direct-text invocations), enabled Game Session main/test Checkstyle, test SpotBugs, formatting and documentation; held main SpotBugs is not rerun. Published #3390 carries this public source; the terminal-cancellation finding is independently qualified by the coupled composition 356 in #3389. Private/ISOLATED/PLAYER_CREATED/AUTO positives, distributed currentness protection, actual canonical runtime cutover, genuine installed delivery/private FRESH/CLOSED aggregation and registration/issuer/custody/activation holds remain unfinished. @@ -568,8 +582,8 @@ With canonical scope consumers absent from the default composition, Account conn | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The historical initial unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped when Docker was unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Previously merged bootstrap credential and connect-scope artifacts use the Account UUID. Ordinary password/OTP results, JWT subjects and profile/export identity fields also use that UUID in this receiving source; profile and legacy runtime/export tenant IDs remain numeric, while public bootstrap, direct-text scope and JOIN results follow the [Account tenant identifier boundary](../../architecture/microservices/account-service/api-contracts.md#account-tenant-identifier-boundary); full portable export is not implemented. The [ordinary UUID receiving record](#ordinary-uuid-issuer-and-receiving) owns the current implementation and proof limits. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and alone do not qualify the later UUID receiving source or production gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. The default public bootstrap discovery, direct-scope, JOIN, and connect-token receiving composition returns `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads. Manually configured receivers follow the [Account API composition boundaries](../../architecture/microservices/account-service/api-contracts.md); connect-token validates bootstrap identity and reads scope but remains held before replay or issuance. The numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary, preserved positive component obligations, and proof history are in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving). Target current-authority and postcondition revalidation remain unproved. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. Prepared JOIN component behavior retains the subscription-row lock boundary, remote scope/target/entitlement checks outside the lock-holding transaction, and atomic membership, operation-outcome, and audit-outbox persistence. These components are not reachable through the default receiving facade. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | -| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountFreshEnrollmentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java); [AccountFreshEnrollmentPolicyRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPolicyRepository.java); [AccountRecentReauthenticationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java); [AccountRecentReauthenticationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java); [V1018__account_fresh_enrollment_certification.sql](../../../services/account-service/src/main/resources/db/migration/V1018__account_fresh_enrollment_certification.sql); [V1018.1__recent_reauthentication_replay_credentials.sql](../../../services/account-service/src/main/resources/db/migration/V1018.1__recent_reauthentication_replay_credentials.sql); [V1018.2](../../../services/account-service/src/main/resources/db/migration/V1018.2__recent_reauthentication_replay_failure_budget.sql); [AccountControlUiCurrentActorVerifier.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java); [V1016__account_recent_reauthentication_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V1016__account_recent_reauthentication_evidence.sql); [V1017__account_global_control_ui_issuance_scope.sql](../../../services/account-service/src/main/resources/db/migration/V1017__account_global_control_ui_issuance_scope.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountFreshEnrollmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java); [AccountGlobalControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java); [AccountGlobalControlUiScopePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java); [AccountRecentReauthenticationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java); [AccountRecentReauthenticationReplayTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java); [AccountControlUiCurrentActorVerifierTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` still fails closed with `501 NOT_IMPLEMENTED` before mutation: the internal recent-reauthentication owner is purpose-bound to self-service game creation and is not wired to factor changes. General factor-change evidence and mutation composition remain open under ADR 0045. Account-global Control-UI, fresh-enrollment certification and purpose-specific recent-reauthentication preparation are present in the sources and focused proof linked here; their receiving limits are recorded below, and they do not establish production registration or custody. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | -| `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [StripeWebhookIntakeService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/StripeWebhookIntakeService.java); [StripeEventInboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/StripeEventInboxRepository.java); [AccountBillingCustomerProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java); [AccountBillingCustomerRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepository.java); [AccountBillingPrerequisiteConfirmationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationService.java); [AccountPaymentInstrumentAttachmentService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java); [AccountPaymentInstrumentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepository.java); [V1026__stripe_event_inbox.sql](../../../services/account-service/src/main/resources/db/migration/V1026__stripe_event_inbox.sql); [V1027__account_billing_customer_and_instrument_owners.sql](../../../services/account-service/src/main/resources/db/migration/V1027__account_billing_customer_and_instrument_owners.sql); [V1027.1__billing_customer_first_dispatch_claim.sql](../../../services/account-service/src/main/resources/db/migration/V1027.1__billing_customer_first_dispatch_claim.sql); [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml); [StripeHostingSubscriptionObserver.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java); [AccountHostingSubscriptionLifecycleRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java); [AccountHostingSubscriptionLifecycleService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java); [AccountSubscriptionIntentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java); [AccountHostingPlanCatalog.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java) | [StripeWebhookIntakePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java); [AccountBillingPrerequisitesPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java); [AccountBillingCustomerDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java); [AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java); [AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java); [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java); [StripeHostingSubscriptionObserverTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java); [AccountHostingSubscriptionLifecycleRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java); [AccountHostingSubscriptionLifecycleServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java); [AccountSubscriptionIntentRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java); [AccountHostingPlanCatalogTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | The first cut adds an unregistered verified Stripe event inbox (V1026), durable customer intent/first-dispatch source (V1027 and V1027.1), and exact-customer saved-method confirmation source. Controlled Stripe SDK/readback and PostgreSQL proof sources do not establish live provider calls or a public route. The unregistered hosting observer, intent, lifecycle and plan sources and their focused unit proof are present. The canonical UUID schema/lifecycle and exact focused proof are present in [canonical billing receiving](#canonical-billing-and-retention-receiving); V1028 retains the original numeric archive, and active canonical ownership uses V1029 and its forward lifecycle migrations. Existing public facade convergence and positive consumers remain in [#3390](https://github.com/benhook1013/FireMUD/pull/3390); `CreateSubscription` still fails closed before mutation. The linked receiving section owns bounded intent/lifecycle/reconciliation and terminal-cancellation proof; production registration, live provider/custody qualification, remaining lifecycle outcomes, complete consumer/runtime enforcement, transfer and replacement-before-detach remain incomplete. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION`; generic provider-mutating substrate is unsupported. Creator/player commerce, donations, fees/shares, payouts, and settlement remain deferred. Webhook intake, billing-customer and saved-method registration additionally require approved finite category schedules, guarded minimization/erasure and account-deletion/backup treatment with physical proof under [the Stripe registration prerequisites](../../architecture/microservices/account-service/stripe-integration.md#billing-owner-source-registration-prerequisites). Append-only provider payloads and card-display history do not authorize indefinite production retention or retention of the Account beyond ADR 0043’s minimum billing-evidence boundary. | +| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountFreshEnrollmentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java); [AccountFreshEnrollmentPolicyRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPolicyRepository.java); [AccountRecentReauthenticationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java); [AccountRecentReauthenticationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java); [V1018__account_fresh_enrollment_certification.sql](../../../services/account-service/src/main/resources/db/migration/V1018__account_fresh_enrollment_certification.sql); [V1018.1__recent_reauthentication_replay_credentials.sql](../../../services/account-service/src/main/resources/db/migration/V1018.1__recent_reauthentication_replay_credentials.sql); [V1018.2](../../../services/account-service/src/main/resources/db/migration/V1018.2__recent_reauthentication_replay_failure_budget.sql); [AccountControlUiCurrentActorVerifier.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java); [V1016__account_recent_reauthentication_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V1016__account_recent_reauthentication_evidence.sql); [V1017__account_global_control_ui_issuance_scope.sql](../../../services/account-service/src/main/resources/db/migration/V1017__account_global_control_ui_issuance_scope.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountFreshEnrollmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java); [AccountGlobalControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java); [AccountGlobalControlUiScopePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java); [AccountRecentReauthenticationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java); [AccountRecentReauthenticationReplayTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java); [AccountControlUiCurrentActorVerifierTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` still fails closed with `501 NOT_IMPLEMENTED` before mutation: the internal recent-reauthentication owner is purpose-bound to self-service game creation and is not wired to factor changes. General factor-change evidence and mutation composition remain open under ADR 0045. Account-global Control-UI, fresh-enrollment certification and purpose-specific recent-reauthentication preparation are present in the sources and focused proof linked here; their receiving limits are recorded below, and they do not establish production registration or custody. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal retained numeric subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; the canonical UUID billing-owner detection gap is recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving), and retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | +| `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [StripeWebhookIntakeService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/StripeWebhookIntakeService.java); [StripeEventInboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/StripeEventInboxRepository.java); [AccountBillingCustomerProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java); [AccountBillingCustomerRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepository.java); [AccountBillingPrerequisiteConfirmationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationService.java); [AccountPaymentInstrumentAttachmentService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java); [AccountPaymentInstrumentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepository.java); [V1026__stripe_event_inbox.sql](../../../services/account-service/src/main/resources/db/migration/V1026__stripe_event_inbox.sql); [V1027__account_billing_customer_and_instrument_owners.sql](../../../services/account-service/src/main/resources/db/migration/V1027__account_billing_customer_and_instrument_owners.sql); [V1027.1__billing_customer_first_dispatch_claim.sql](../../../services/account-service/src/main/resources/db/migration/V1027.1__billing_customer_first_dispatch_claim.sql); [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml); [StripeHostingSubscriptionProvisioner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java); [AccountHostingSubscriptionProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java); [StripeHostingSubscriptionObserver.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java); [AccountHostingSubscriptionLifecycleRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java); [AccountHostingSubscriptionLifecycleService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java); [AccountSubscriptionIntentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java); [AccountHostingPlanCatalog.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java) | [StripeWebhookIntakePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java); [AccountBillingPrerequisitesPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java); [AccountBillingCustomerDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java); [AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java); [AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java); [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java); [StripeHostingSubscriptionProvisionerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java); [AccountHostingSubscriptionProvisioningServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java); [AccountHostingSubscriptionDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java); [StripeHostingSubscriptionObserverTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java); [AccountHostingSubscriptionLifecycleRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java); [AccountHostingSubscriptionLifecycleServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java); [AccountSubscriptionIntentRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java); [AccountHostingPlanCatalogTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | The first cut adds an unregistered verified Stripe event inbox (V1026), durable customer intent/first-dispatch source (V1027 and V1027.1), and exact-customer saved-method confirmation source. Controlled Stripe SDK/readback and PostgreSQL proof sources do not establish live provider calls or a public route. The unregistered hosting observer, intent, lifecycle and plan sources and their focused unit proof are present. The canonical UUID schema/lifecycle and exact focused proof are present in [canonical billing receiving](#canonical-billing-and-retention-receiving); V1028 retains the original numeric archive, and active canonical ownership uses V1029 and its forward lifecycle migrations. Existing public facade convergence and positive consumers remain in [#3390](https://github.com/benhook1013/FireMUD/pull/3390); `CreateSubscription` still fails closed before mutation. The linked receiving section owns bounded intent/lifecycle/reconciliation and terminal-cancellation proof; production registration, live provider/custody qualification, remaining lifecycle outcomes, complete consumer/runtime enforcement, transfer and replacement-before-detach remain incomplete. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION`; generic provider-mutating substrate is unsupported. Creator/player commerce, donations, fees/shares, payouts, and settlement remain deferred. Webhook intake, billing-customer and saved-method registration additionally require approved finite category schedules, guarded minimization/erasure and account-deletion/backup treatment with physical proof under [the Stripe registration prerequisites](../../architecture/microservices/account-service/stripe-integration.md#billing-owner-source-registration-prerequisites). Append-only provider payloads and card-display history do not authorize indefinite production retention or retention of the Account beyond ADR 0043’s minimum billing-evidence boundary. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The current numeric runtime entitlement endpoint returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Current status, preserved positive receiving obligations, and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving); earlier focused storage/retry proof does not establish a live legacy-row producer. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance follows the [Account API conditional bootstrap/scope validation boundary](../../architecture/microservices/account-service/api-contracts.md#rest-apis), but remains unavailable before entitlement reads, cached replay, or token issuance; older positive-issuance tests are historical. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its shared subscription-version/billing-sequence projection and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. No current gameplay or public-join eligibility is inferred from a retained numeric `past_due` row while the runtime entitlement boundary is held. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation when canonical scope consumers are absent; when manually configured, it validates bootstrap identity and reads the connect scope before refusing cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. Current WebSocket reconnect suppresses retained private-context presentation while durable episode/generation eligibility is unqualified; rows remain stored, so this is neither deletion nor proof of logout invalidation. R1424 executed bounded suppression/redraw proof (57 WebSocket-handler units, 20 integration cases and ten LOOK cross-service cases), separately attributed in [Reconnect and Continuity](#reconnect-and-continuity); this is not a fresh current-head image result or proof of eligible-context replay. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | @@ -883,6 +897,7 @@ The #3367 image smoke at `e139ee01` fails when Entity’s explicitly enabled dem - Account switching, multi-session controls, global sign-out, and richer first-party logout UX are not implemented. The designed Account Service `/auth/logout` and `/auth/logout-all` control-plane routes and issuer/account/tenant/membership authority-generation workflows are also absent from production code. - Gameplay presence classification ignores global roles and derives elevation only from explicit current-tenant gameplay roles. Production tenant-gameplay-grant qualification remains incomplete as recorded in [EA-2.3](./player-experience-commands-and-communication.md#communication-social-and-presence); no staff impersonation or hidden-observer mode is part of the target. - Account hard-delete currently fails closed; retained payment and subscription lifecycle and deletion reconciliation remain incomplete. +- The billing-owner deletion precondition does not yet inspect nonterminal canonical UUID subscriptions. Once the retained-JOIN blocker is clear, a canonical-only billing owner receives `ACCOUNT_DELETE_UNAVAILABLE` instead of `ACCOUNT_DELETE_ACTIVE_BILLING_OWNER`. Account's retention/deletion owner must add the canonical current-owner check and positive/negative proof before enabling deletion, preserving retained-history blockers; see [canonical billing and retention receiving](#canonical-billing-and-retention-receiving). - Account deletion also remains blocked by any retained JOIN operation row, including terminal receipts, through the current fail-closed `hasRetainedOperation` guard. Bounded JOIN receipt cleanup/minimization and deletion reconciliation are not implemented; Account's retention/deletion workflow owns them under [ADR 0163](../../architecture/decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) and [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md), dependent on #2848 JOIN receipt and unknown-outcome reconciliation. No universal retention duration is selected. - Account security-lock, ban, suspension, operator recovery, and appeal handling are not a complete end-to-end cross-service flow. The current `AUTH_ACCOUNT_LOCKED`, moderation, and lifecycle boundaries must converge without making Logging & Admin the owner of Account enforcement. - Automated signing-key rotation, overlap/pruning, and deployment-wide validator-convergence proof remain deferred even though JWKS publication and conditional file watching are live. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java new file mode 100644 index 0000000000..f491949494 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java @@ -0,0 +1,243 @@ +package net.firedevops.firemud.accountservice.client; + +import com.stripe.exception.StripeException; +import com.stripe.model.StripeSearchResult; +import com.stripe.model.Subscription; +import com.stripe.net.RequestOptions; +import com.stripe.param.SubscriptionCreateParams; +import com.stripe.param.SubscriptionListParams; +import com.stripe.param.SubscriptionSearchParams; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Clock; +import java.time.Duration; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Held initial hosting-subscription SDK adapter. Only a private, independently read durable owner + * dispatch supplies its explicit customer, instrument, quote and initial-call permission. Existing + * or pre-migration unknown dispatches reconcile only; no empty search authorizes recreation. No + * actor authorization, update/cancel command, runtime registration or entitlement is supplied. + */ +public final class StripeHostingSubscriptionProvisioner { + private static final long MAX_PROVIDER_SUBSCRIPTIONS_PER_CUSTOMER = 100L; + + private final com.stripe.StripeClient stripe; + private final Clock clock; + private final RequestOptions requestOptions; + private final StripeHostingSubscriptionObserver observer; + private final StripeBillingPrerequisiteObserver prerequisites; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected SDK/repository collaborators remain private; copying would break owner composition.") + public StripeHostingSubscriptionProvisioner( + com.stripe.StripeClient stripe, + Clock clock, + boolean expectedLivemode, + Duration connectTimeout, + Duration readTimeout) { + this.stripe = Objects.requireNonNull(stripe); + this.clock = Objects.requireNonNull(clock); + observer = new StripeHostingSubscriptionObserver(stripe, clock, connectTimeout, readTimeout); + // The observer validates positive whole-millisecond SDK limits before this conversion. + requestOptions = + RequestOptions.builder() + .setConnectTimeout(Math.toIntExact(connectTimeout.toMillis())) + .setReadTimeout(Math.toIntExact(readTimeout.toMillis())) + .setMaxNetworkRetries(0) + .build(); + prerequisites = new StripeBillingPrerequisiteObserver(stripe, clock, expectedLivemode); + } + + public Result provision(ProviderDispatch dispatch) { + Objects.requireNonNull(dispatch); + requireNoTransaction(); + if (!dispatch.readyForProviderIo()) { + throw new IllegalStateException( + "Committed independent provider-dispatch readback is required"); + } + if (!live(dispatch)) { + return new Pending("DISPATCH_LEASE_EXPIRED", null); + } + var creation = dispatch.claim().creation(); + // Local reservations do not prove that the provider's instrument is still attached. + var prerequisite = + prerequisites.observe( + new StripeBillingPrerequisiteObserver.ExpectedBinding( + creation.owner().accountUuid(), + creation.customerProvisioningRequestId(), + dispatch.customerProviderIdempotencyId(), + creation.providerCustomerId(), + dispatch.providerPaymentMethodId()), + requestOptions); + if (!(prerequisite instanceof StripeBillingPrerequisiteObserver.ObservedBillingPrerequisites)) { + return new Pending("PROVIDER_PREREQUISITES_UNRESOLVED", null); + } + if (!live(dispatch)) { + return new Pending("DISPATCH_LEASE_EXPIRED", null); + } + Map metadata = + Map.of( + "firemud_metadata_schema_version", + "1", + "firemud_operation_type", + "subscription_provisioning", + "firemud_operation_id", + creation.subscriptionProvisioningRequestId().toString(), + "firemud_subscription_id", + creation.subscriptionId().toString()); + try { + String query = + "metadata['firemud_metadata_schema_version']:'1' AND " + + "metadata['firemud_operation_type']:'subscription_provisioning' AND " + + "metadata['firemud_operation_id']:'" + + creation.subscriptionProvisioningRequestId() + + "' AND metadata['firemud_subscription_id']:'" + + creation.subscriptionId() + + "'"; + StripeSearchResult matches = + stripe + .subscriptions() + .search( + SubscriptionSearchParams.builder().setQuery(query).setLimit(2L).build(), + requestOptions); + if (matches == null + || matches.getData() == null + || !Boolean.FALSE.equals(matches.getHasMore()) + || matches.getData().size() > 1) { + return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_SEARCH", null); + } + Subscription candidate; + if (matches.getData().isEmpty()) { + if (!dispatch.initialCallAllowed()) { + if (!live(dispatch)) { + return new Pending("DISPATCH_LEASE_EXPIRED", null); + } + var listed = + stripe + .subscriptions() + .list( + SubscriptionListParams.builder() + .setCustomer(creation.providerCustomerId()) + .setStatus(SubscriptionListParams.Status.ALL) + .setLimit(MAX_PROVIDER_SUBSCRIPTIONS_PER_CUSTOMER) + .build(), + requestOptions); + if (listed == null + || listed.getData() == null + || !Boolean.FALSE.equals(listed.getHasMore()) + || listed.getData().size() > MAX_PROVIDER_SUBSCRIPTIONS_PER_CUSTOMER) { + return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null); + } + candidate = null; + for (Subscription listedCandidate : listed.getData()) { + if (listedCandidate == null) { + return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null); + } + if (metadata.equals(listedCandidate.getMetadata())) { + if (!creation.providerCustomerId().equals(listedCandidate.getCustomer())) { + return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null); + } + if (candidate != null) { + return new Pending("INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null); + } + candidate = listedCandidate; + } + } + if (candidate == null) { + return new Pending("PROVIDER_LOOKUP_UNRESOLVED", null); + } + } else { + if (!live(dispatch)) { + return new Pending("DISPATCH_LEASE_EXPIRED", null); + } + candidate = + stripe + .subscriptions() + .create( + SubscriptionCreateParams.builder() + .setCustomer(creation.providerCustomerId()) + .setDefaultPaymentMethod(dispatch.providerPaymentMethodId()) + .setCollectionMethod( + SubscriptionCreateParams.CollectionMethod.CHARGE_AUTOMATICALLY) + .setPaymentBehavior( + SubscriptionCreateParams.PaymentBehavior.DEFAULT_INCOMPLETE) + .addItem( + SubscriptionCreateParams.Item.builder() + .setPrice(creation.planQuote().providerPriceId()) + .setQuantity(creation.planQuote().providerQuantity()) + .build()) + .putAllMetadata(metadata) + .build(), + requestOptions + .toBuilderFullCopy() + .setIdempotencyKey( + creation.subscriptionProvisioningRequestId().toString()) + .build()); + } + } else { + candidate = matches.getData().getFirst(); + } + // Candidate status is never authority. Exact identity and metadata only select readback. + if (candidate == null + || !"subscription".equals(candidate.getObject()) + || candidate.getId() == null + || !candidate.getId().matches("sub_[A-Za-z0-9]{1,251}") + || !metadata.equals(candidate.getMetadata())) { + return new Pending("PROVIDER_CANDIDATE_BINDING_INVALID", null); + } + if (!live(dispatch)) { + return new Pending("DISPATCH_LEASE_EXPIRED", null); + } + var observed = observer.observe(dispatch.expectedBinding(candidate.getId())); + if (!(observed instanceof StripeHostingSubscriptionObserver.ObservedSubscription actual)) { + return new Pending("INDEPENDENT_PROVIDER_READBACK_UNRESOLVED", null); + } + return new Located(actual); + } catch (StripeException failure) { + return new Pending("PROVIDER_OUTCOME_UNKNOWN", failure); + } + } + + private boolean live(ProviderDispatch dispatch) { + var now = clock.instant(); + return !now.isBefore(dispatch.claim().claimedAt()) + && now.isBefore(dispatch.claim().expiresAt()); + } + + private static void requireNoTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Hosting provider IO refuses an ambient SQL transaction"); + } + } + + public sealed interface Result permits Pending, Located {} + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "The SDK exception is an internal diagnostic cause, never provider authority or a public response.") + public record Pending(String reason, StripeException providerFailure) implements Result {} + + /** Locator plus genuine private observer evidence; lifecycle commit independently reads again. */ + public static final class Located implements Result { + private final StripeHostingSubscriptionObserver.ObservedSubscription observation; + + private Located(StripeHostingSubscriptionObserver.ObservedSubscription observation) { + this.observation = observation; + } + + public StripeHostingSubscriptionObserver.ObservedSubscription observation() { + return observation; + } + + public String providerSubscriptionId() { + return observation.providerSubscriptionId(); + } + } +} 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 edd338b5fa..246fc7383b 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 @@ -1221,20 +1221,16 @@ public ClaimResult claim(UUID requestId, long expectedRowVersion, UUID attemptId } long versionToLock = prior == null ? expectedRowVersion : prior.get("claimed_row_version", Long.class); - var current = intents.lockForProvisioningRecovery(requestId, versionToLock); + AccountSubscriptionCurrentRecord current; + try { + current = intents.lockForProvisioningRecovery(requestId, versionToLock); + } catch (FenceRejectedException refused) { + // A later wallet observation may prevent even the first dispatch. The original intent + // can use the local settlement fence, but this path never returns a provider-capable claim. + return recoverUndispatchableWork(requestId, versionToLock, prior); + } var original = intents.findCreation(requestId).orElseThrow(); - dsl.execute( - "INSERT INTO subscription_provisioning_work (request_id, subscription_id, phase, row_version, " - + "attempt_count, max_attempts, max_stalled_attempts, lease_millis, backoff_millis, deadline_at, retry_at) " - + "VALUES (?, ?, 'RECONCILING', 1, 0, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz) ON CONFLICT (request_id) DO NOTHING", - requestId, - original.subscriptionId(), - limits.maximumAttempts(), - limits.maximumStalledAttempts(), - limits.lease().toMillis(), - limits.backoff().toMillis(), - utc(original.createdAt().plus(limits.absoluteTimeout())), - utc(original.createdAt())); + retainUnclaimedWork(original); Record work = workForUpdate(requestId); Instant now = databaseNow(); if (now.isBefore(original.createdAt())) { @@ -1323,6 +1319,93 @@ public ClaimResult claim(UUID requestId, long expectedRowVersion, UUID attemptId return new ClaimResult(Disposition.CLAIMED, claim(original, Objects.requireNonNull(attempt))); } + private void retainUnclaimedWork(AccountSubscriptionCreationRecord original) { + dsl.execute( + "INSERT INTO subscription_provisioning_work (request_id, subscription_id, phase, row_version, " + + "attempt_count, max_attempts, max_stalled_attempts, lease_millis, backoff_millis, deadline_at, retry_at) " + + "VALUES (?, ?, 'RECONCILING', 1, 0, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz) ON CONFLICT (request_id) DO NOTHING", + original.requestId(), + original.subscriptionId(), + limits.maximumAttempts(), + limits.maximumStalledAttempts(), + limits.lease().toMillis(), + limits.backoff().toMillis(), + utc(original.createdAt().plus(limits.absoluteTimeout())), + utc(original.createdAt())); + } + + private ClaimResult recoverUndispatchableWork(UUID requestId, long version, Record prior) { + var current = intents.lockForProvisioningSettlement(requestId, version); + var original = intents.findCreation(requestId).orElseThrow(); + retainUnclaimedWork(original); + Record work = workForUpdate(requestId); + Instant now = databaseNow(); + if (now.isBefore(original.createdAt())) { + throw new FenceRejectedException("Provisioning clock predates the durable intent"); + } + if (work.get("last_attempt_id") == null) { + if (prior != null + || work.get("attempt_count", Integer.class) != 0 + || !current.subscriptionId().equals(work.get("subscription_id", UUID.class)) + || !"pending".equals(current.status()) + || current.rowVersion() != 1L + || current.providerSubscriptionId() != null + || links(current.subscriptionId()).get("lifecycle_inflight_request_id") != null) { + throw new FenceRejectedException("Exact unclaimed provisioning settlement fence rejected"); + } + if ("BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(work.get("phase", String.class))) { + return new ClaimResult(Disposition.TERMINAL_FAILURE, null); + } + if (!"RECONCILING".equals(work.get("phase", String.class))) { + throw new FenceRejectedException("Unclaimed provisioning work is not reconciling"); + } + // No claim is issued and no provider absence is inferred. Keep the reservation held and + // retain one operator item even when the wallet changed before work was first claimed. + return fail(work, "RESERVED_INSTRUMENT_CHANGED", now); + } + requireUnmappedProvisioningWork(current, work); + if (prior != null + && !prior.get("attempt_id", UUID.class).equals(work.get("last_attempt_id", UUID.class))) { + return new ClaimResult(Disposition.ATTEMPT_EXPIRED, null); + } + Record retained = + dsl.fetchOne( + "SELECT * FROM subscription_provisioning_attempts WHERE attempt_id = ?", + work.get("last_attempt_id", UUID.class)); + if (retained == null || now.isBefore(instant(retained, "claimed_at"))) { + throw new FenceRejectedException("Exact retained provisioning attempt is absent or future"); + } + if ("BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(work.get("phase", String.class))) { + return new ClaimResult(Disposition.TERMINAL_FAILURE, null); + } + if (!now.isBefore(instant(work, "deadline_at"))) { + return fail(work, "ABSOLUTE_DEADLINE", now); + } + if ("CLAIMED".equals(work.get("phase", String.class)) + && now.isBefore(instant(work, "lease_expires_at"))) { + return new ClaimResult(Disposition.WAITING, null); + } + if (work.get("attempt_count", Integer.class) >= work.get("max_attempts", Integer.class)) { + return fail(work, "ATTEMPT_BUDGET", now); + } + if (work.get("attempt_count", Integer.class) + >= work.get("max_stalled_attempts", Integer.class)) { + return fail(work, "STALLED_WITHOUT_COMMITTED_PROGRESS", now); + } + return new ClaimResult(Disposition.WAITING, null); + } + + private void requireUnmappedProvisioningWork( + AccountSubscriptionCurrentRecord current, Record work) { + if (!current.subscriptionId().equals(work.get("subscription_id", UUID.class)) + || !Objects.equals(current.rowVersion(), work.get("subscription_row_version", Long.class)) + || work.get("last_attempt_id") == null + || current.providerSubscriptionId() != null + || links(current.subscriptionId()).get("lifecycle_inflight_request_id") != null) { + throw new FenceRejectedException("Exact unmapped retained provisioning work fence rejected"); + } + } + /** * Inserts a separate immutable provider-dispatch boundary after revalidating the exact live * private worker claim. Only a newly inserted first-dispatch receipt may carry initial-call @@ -1559,9 +1642,27 @@ public ExpectedBinding expectedBinding(String providerId) { public Disposition deferUnresolved(ProvisioningClaim claim) { requireTransaction(); Objects.requireNonNull(claim); - intents.lockForProvisioningRecovery( - claim.creation().requestId(), claim.subscriptionRowVersion()); + var current = + intents.lockForProvisioningSettlement( + claim.creation().requestId(), claim.subscriptionRowVersion()); Record work = workForUpdate(claim.creation().requestId()); + requireUnmappedProvisioningWork(current, work); + Record retained = + dsl.fetchOne( + "SELECT * FROM subscription_provisioning_attempts WHERE attempt_id = ?", + claim.attemptId()); + if (retained == null + || !claim + .creation() + .equals(intents.findCreation(claim.creation().requestId()).orElseThrow()) + || !claim.creation().requestId().equals(retained.get("request_id", UUID.class)) + || !claim.creation().subscriptionId().equals(retained.get("subscription_id", UUID.class)) + || claim.attemptNumber() != retained.get("attempt_number", Integer.class) + || claim.subscriptionRowVersion() != retained.get("claimed_row_version", Long.class) + || !claim.claimedAt().equals(instant(retained, "claimed_at")) + || !claim.expiresAt().equals(instant(retained, "expires_at"))) { + throw new FenceRejectedException("Exact retained provisioning settlement claim rejected"); + } Instant now = databaseNow(); if (now.isBefore(claim.claimedAt())) { throw new FenceRejectedException("Provisioning clock predates its retained claim"); @@ -1573,12 +1674,12 @@ public Disposition deferUnresolved(ProvisioningClaim claim) { if ("BILLING_RECONCILIATION_TERMINAL_FAILURE".equals(phase)) { return Disposition.TERMINAL_FAILURE; } - if ("RECONCILING".equals(phase)) { - return Disposition.WAITING; - } if (!now.isBefore(instant(work, "deadline_at"))) { return fail(work, "ABSOLUTE_DEADLINE", now).disposition(); } + if ("RECONCILING".equals(phase)) { + return Disposition.WAITING; + } if (!now.isBefore(claim.expiresAt())) { // The exact retained attempt expired without a provider completion. Leave its work and // reservation untouched for the next claimant rather than treating normal expiry as a fault. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java index a453192439..f92bedbf5f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java @@ -212,16 +212,29 @@ public AccountSubscriptionCurrentRecord lockForProvisioningRecovery( */ public AccountSubscriptionCurrentRecord lockForLifecycle( UUID requestId, long expectedRowVersion) { - return lockBinding(requestId, expectedRowVersion, true, true); + return lockBinding(requestId, expectedRowVersion, true, true, true); + } + + /** + * Local settlement only for retained provisioning work. Later wallet observations cannot strand + * its original reservation, but this lock never authorizes a claim or provider dispatch. + */ + AccountSubscriptionCurrentRecord lockForProvisioningSettlement( + UUID requestId, long expectedRowVersion) { + return lockBinding(requestId, expectedRowVersion, true, false, true); } private AccountSubscriptionCurrentRecord lockProvisioningBinding( UUID requestId, long expectedRowVersion, boolean allowProvisioning) { - return lockBinding(requestId, expectedRowVersion, allowProvisioning, false); + return lockBinding(requestId, expectedRowVersion, allowProvisioning, false, false); } private AccountSubscriptionCurrentRecord lockBinding( - UUID requestId, long expectedRowVersion, boolean allowProvisioning, boolean lifecycle) { + UUID requestId, + long expectedRowVersion, + boolean allowProvisioning, + boolean lifecycle, + boolean allowInstrumentObservation) { requireWritableTransaction(); AccountBillingCustomerRecord.requireUuid(requestId); if (expectedRowVersion < 1) { @@ -239,7 +252,7 @@ private AccountSubscriptionCurrentRecord lockBinding( currentForUpdate(original.tenantId()) .orElseThrow(() -> new FenceRejectedException("Current subscription is absent")); boolean instrumentVersionAndStateMatch = - lifecycle + allowInstrumentObservation ? instrument.rowVersion() >= original.reservedInstrumentVersion() && (instrument.state() == AccountPaymentInstrumentRecord.State.ATTACHABLE || instrument.state() == AccountPaymentInstrumentRecord.State.UNAVAILABLE) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java new file mode 100644 index 0000000000..3460cbe732 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java @@ -0,0 +1,146 @@ +package net.firedevops.firemud.accountservice.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionProvisioner; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionCurrentReceipt; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Disposition; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.TransitionResult; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Held owner composition for an existing genuine private provisioning claim. This does not admit + * CreateSubscription callers or register any bean/route/worker. The authenticated create producer, + * production custody and deployment remain held. Dispatch commits and independent owner readback + * precede provider IO; provider output cannot directly write status or confer entitlement. Existing + * lifecycle reconciliation performs its own SDK read, fenced commit, then independent current read. + */ +public final class AccountHostingSubscriptionProvisioningService { + private final AccountHostingSubscriptionLifecycleRepository repository; + private final StripeHostingSubscriptionProvisioner provider; + private final AccountHostingSubscriptionLifecycleService lifecycle; + private final TransactionTemplate transaction; + + public AccountHostingSubscriptionProvisioningService( + AccountHostingSubscriptionLifecycleRepository repository, + StripeHostingSubscriptionProvisioner provider, + AccountHostingSubscriptionLifecycleService lifecycle, + PlatformTransactionManager transactions) { + this.repository = Objects.requireNonNull(repository); + this.provider = Objects.requireNonNull(provider); + this.lifecycle = Objects.requireNonNull(lifecycle); + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + public Result provision(ProvisioningClaim claim, UUID dispatchId, UUID lifecycleRequestId) { + Objects.requireNonNull(claim, "Existing genuine owner provisioning claim is required"); + requireUuid(dispatchId); + requireUuid(lifecycleRequestId); + requireNoAmbientTransaction(); + ProviderDispatch dispatch; + try { + var prepared = + Objects.requireNonNull( + transaction.execute(status -> repository.prepareProviderDispatch(claim, dispatchId))); + dispatch = + Objects.requireNonNull( + transaction.execute(status -> repository.readProviderDispatch(prepared))); + } catch (FenceRejectedException refused) { + // Dispatch remains strictly fenced. A new local transaction may only settle the same retained + // work; stale/current-owner/reservation mismatches still reject there before any write. + Disposition disposition = + Objects.requireNonNull(transaction.execute(status -> repository.deferUnresolved(claim))); + return new Pending( + disposition, + new StripeHostingSubscriptionProvisioner.Pending("DISPATCH_FENCE_REJECTED", null)); + } + requireNoAmbientTransaction(); + var located = provider.provision(dispatch); + if (!(located instanceof StripeHostingSubscriptionProvisioner.Located actual)) { + Disposition disposition = + Objects.requireNonNull( + transaction.execute(status -> repository.deferUnresolved(dispatch.claim()))); + return new Pending(disposition, located); + } + // Locator and actual observation select the existing owner operation, never an ad-hoc write. + TransitionResult transition = + lifecycle.reconcile( + lifecycleRequestId, + claim.creation().requestId(), + claim.subscriptionRowVersion(), + actual.providerSubscriptionId(), + claim.attemptId()); + if (transition.outcome() != Outcome.COMMITTED) { + return new Reconciling(transition); + } + AccountHostingSubscriptionCurrentReceipt current; + try { + current = lifecycle.readCurrent(claim.creation().tenantId()); + } catch ( + AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException unavailable) { + return new ReadbackUnavailable(transition); + } + if (!current.receiptRequestId().equals(lifecycleRequestId) + || current.current().rowVersion() != transition.committedRowVersion() + || !current.current().subscriptionId().equals(claim.creation().subscriptionId()) + || !current.current().creationRequestId().equals(claim.creation().requestId()) + || !actual.providerSubscriptionId().equals(current.current().providerSubscriptionId()) + || !current.current().planQuote().equals(claim.creation().planQuote())) { + throw new IllegalStateException("Independent committed hosting receipt readback mismatch"); + } + return new Committed(transition, current); + } + + private static void requireUuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("Non-nil hosting operation identity is required"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Hosting provisioner refuses an ambient SQL transaction"); + } + } + + public sealed interface Result permits Pending, Reconciling, ReadbackUnavailable, Committed {} + + public record Pending( + Disposition disposition, StripeHostingSubscriptionProvisioner.Result providerResult) + implements Result {} + + public record Reconciling(TransitionResult transition) implements Result {} + + /** The transition committed, but a fresh current receipt could not be obtained. */ + public record ReadbackUnavailable(TransitionResult transition) implements Result {} + + /** Privately constructed after actual lifecycle commit and independent current readback. */ + public static final class Committed implements Result { + private final TransitionResult transition; + private final AccountHostingSubscriptionCurrentReceipt current; + + private Committed( + TransitionResult transition, AccountHostingSubscriptionCurrentReceipt current) { + this.transition = transition; + this.current = current; + } + + public TransitionResult transition() { + return transition; + } + + public AccountHostingSubscriptionCurrentReceipt current() { + return current; + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java index e40b79cd69..79c1169e9b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java @@ -5,6 +5,7 @@ import static org.mockito.Mockito.mock; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -24,6 +25,7 @@ import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.SQLDialect; @@ -281,6 +283,188 @@ void migrationRetainsV1AndStoresExactV2ScopeAndPendingIntentWithoutMembershipOrE .isZero(); } + @Test + void receivingUpgradeFromParent1036Through1038PreservesCanonicalRowsAndHistory() { + String schema = createSchema("canonical_join_scope_"); + DriverManagerDataSource dataSource = postgres.dataSource(schema); + Flyway parent = accountFlyway(dataSource, schema, "1036"); + parent.migrate(); + parent.validate(); + assertThat(parent.info().current().getVersion()) + .isEqualTo(MigrationVersion.fromVersion("1036")); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + Record account = + setupDsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) " + + "RETURNING id, account_uuid", + "canonical-migration-upgrade-account", + "canonical-migration-upgrade@example.test", + "test-hash"); + long privateAccountId = Objects.requireNonNull(account).get("id", Long.class); + UUID accountUuid = Objects.requireNonNull(account).get("account_uuid", UUID.class); + + FreshTenantIdentityAssociationRepository freshTenants = + new FreshTenantIdentityAssociationRepository(transactionDsl, "prod"); + FreshTenantCreationEvidence tenantSource = freshTenantEvidence(); + transaction.executeWithoutResult(status -> freshTenants.importVerified(tenantSource)); + AccountConnectScopeRepository scopes = + new AccountConnectScopeRepository( + transactionDsl, mock(AccountTenantIdentityResolver.class), freshTenants); + AccountJoinOperationRepository operations = + new AccountJoinOperationRepository(transactionDsl, scopes); + CanonicalJoinScopeV2 scope = canonicalScope(accountUuid, tenantSource.canonicalTenantId()); + VerifiedTenantProvenance tenantProvenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantSource.operationId(), + tenantSource.evidenceDigest()); + String requestId = "canonical-migration-upgrade-pending"; + String callerBinding = "canonical-migration-upgrade-caller"; + transaction.executeWithoutResult( + status -> { + scopes.insertCanonical(privateAccountId, scope, tenantProvenance); + assertThat(operations.insertCanonicalIntent(requestId, scope, callerBinding)).isTrue(); + }); + CanonicalJoinOperationEvidence pending = + transaction.execute( + status -> operations.findCanonicalEvidenceByRequestId(requestId).orElseThrow()); + assertThat(pending.status()).isEqualTo("PENDING"); + + String scopeTokenHash = AccountJoinDigest.tokenHash(scope.connectScopeId()); + RetainedPhysicalRow retainedScope = + retainedPhysicalRow( + setupDsl, + "SELECT to_jsonb(scope_row)::text, scope_row.xmin::text " + + "FROM account_connect_scope_records scope_row WHERE scope_token_hash = ?", + scopeTokenHash); + RetainedPhysicalRow retainedIntent = + retainedPhysicalRow( + setupDsl, + "SELECT to_jsonb(operation_row)::text, operation_row.xmin::text " + + "FROM account_join_operations operation_row WHERE request_id = ?", + requestId); + List> parentHistory = flywayHistory(setupDsl); + assertThat(parentHistory) + .extracting(row -> row.get("script")) + .contains("V1036__hosting_subscription_terminal_resolution.sql") + .doesNotContain( + "V1037__canonical_join_failure_and_attempt_diagnostics.sql", + "V1038__canonical_join_existing_membership_terminal.sql"); + + Flyway current = accountFlyway(dataSource, schema, "1038"); + current.migrate(); + current.validate(); + assertThat(current.info().current().getVersion()) + .isEqualTo(MigrationVersion.fromVersion("1038")); + + List> upgradedHistory = flywayHistory(setupDsl); + assertThat(upgradedHistory).hasSize(parentHistory.size() + 2); + assertThat(upgradedHistory.subList(0, parentHistory.size())) + .containsExactlyElementsOf(parentHistory); + List> addedHistory = + upgradedHistory.subList(parentHistory.size(), upgradedHistory.size()); + assertThat(addedHistory).extracting(row -> row.get("version")).containsExactly("1037", "1038"); + assertThat(addedHistory) + .extracting(row -> row.get("script")) + .containsExactly( + "V1037__canonical_join_failure_and_attempt_diagnostics.sql", + "V1038__canonical_join_existing_membership_terminal.sql"); + assertThat(addedHistory) + .allSatisfy( + row -> { + assertThat(row.get("checksum")).isNotNull(); + assertThat(row.get("success")).isEqualTo(true); + }); + assertThat( + retainedPhysicalRow( + setupDsl, + "SELECT to_jsonb(scope_row)::text, scope_row.xmin::text " + + "FROM account_connect_scope_records scope_row WHERE scope_token_hash = ?", + scopeTokenHash)) + .isEqualTo(retainedScope); + assertThat( + retainedPhysicalRow( + setupDsl, + "SELECT to_jsonb(operation_row)::text, operation_row.xmin::text " + + "FROM account_join_operations operation_row WHERE request_id = ?", + requestId)) + .isEqualTo(retainedIntent); + + List installedConstraints = + setupDsl + .fetch( + "SELECT constraint_row.conname FROM pg_constraint constraint_row " + + "JOIN pg_class table_row ON table_row.oid = constraint_row.conrelid " + + "JOIN pg_namespace schema_row ON schema_row.oid = table_row.relnamespace " + + "WHERE schema_row.nspname = ? AND table_row.relname = 'account_join_operations' " + + "AND constraint_row.contype = 'c' AND constraint_row.convalidated", + schema) + .getValues(0, String.class); + assertThat(installedConstraints) + .contains( + "account_join_v2_attempt_diagnostics_check", + "account_join_exact_first_transition_check", + "account_join_operation_representation_check", + "account_join_canonical_terminal_proof_check"); + assertThat( + Objects.requireNonNull( + setupDsl.fetchOne( + "SELECT count(*) FROM pg_trigger trigger_row " + + "JOIN pg_class table_row ON table_row.oid = trigger_row.tgrelid " + + "JOIN pg_namespace schema_row ON schema_row.oid = table_row.relnamespace " + + "WHERE schema_row.nspname = ? AND table_row.relname = 'account_join_operations' " + + "AND trigger_row.tgname = 'account_join_operation_identity_guard' " + + "AND trigger_row.tgenabled = 'O' AND NOT trigger_row.tgisinternal", + schema)) + .get(0, Long.class)) + .isEqualTo(1L); + String guardDefinition = + Objects.requireNonNull( + setupDsl.fetchOne( + "SELECT pg_get_functiondef(?::regprocedure)", + schema + ".guard_account_join_operation_identity()")) + .get(0, String.class); + assertThat(guardDefinition) + .contains("ALREADY_ACTIVE", "account_tenant_membership", "last_attempt_failure_code"); + + CanonicalJoinOperationEvidence diagnosed = + transaction.execute( + status -> + operations.recordCanonicalAttemptFailure( + requestId, scope, callerBinding, "NOT_EVALUATED", "AUTH_UNAVAILABLE")); + assertThat(diagnosed.status()).isEqualTo("PENDING"); + assertThat(diagnosed.lastAttemptAuthorityAvailability()).isEqualTo("NOT_EVALUATED"); + assertThat(diagnosed.lastAttemptFailureCode()).isEqualTo("AUTH_UNAVAILABLE"); + RetainedPhysicalRow diagnosedIntent = + retainedPhysicalRow( + setupDsl, + "SELECT to_jsonb(operation_row)::text, operation_row.xmin::text " + + "FROM account_join_operations operation_row WHERE request_id = ?", + requestId); + assertThatThrownBy( + () -> + setupDsl.execute( + "UPDATE account_join_operations SET verified_caller_binding = ? WHERE request_id = ?", + "changed-migration-caller", + requestId)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + assertThat( + retainedPhysicalRow( + setupDsl, + "SELECT to_jsonb(operation_row)::text, operation_row.xmin::text " + + "FROM account_join_operations operation_row WHERE request_id = ?", + requestId)) + .isEqualTo(diagnosedIntent); + } + @Test void expiredScopeCleanupSkipsImmutableV2BeforeLimitingV1Batch() { String schema = createSchema("canonical_scope_cleanup_"); @@ -363,6 +547,475 @@ void expiredScopeCleanupSkipsImmutableV2BeforeLimitingV1Batch() { assertThat(scopeRowCount(setupDsl, v2Scope.connectScopeId())).isEqualTo(1); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void definitiveFailureRetainsOriginalIntentAndOptionalPolicyAndExactlyReplaysWithoutRewrite( + boolean bound) { + JournalFixture f = journalFixture(); + if (bound) + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); + else + f.transaction() + .execute( + status -> + f.operations() + .recordCanonicalPolicyUnavailable( + f.requestId(), f.scope(), f.caller(), "ENTITLEMENT_UNAVAILABLE")); + var original = f.read(); + String outcome = bound ? "IDEMPOTENCY_CONFLICT" : "CONNECT_SCOPE_INVALID"; + var failed = + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure(f.requestId(), f.scope(), f.caller(), outcome)); + assertThat(failed.status()).isEqualTo("FAILED"); + assertThat(failed.outcome()).isEqualTo(outcome); + assertThat(failed.intentDigest()).isEqualTo(original.intentDigest()); + assertThat(failed.scopeEvidence()).isEqualTo(original.scopeEvidence()); + assertThat(failed.requestDigest()).isEqualTo(original.requestDigest()); + assertThat(failed.requestDigestVersion()).isEqualTo(original.requestDigestVersion()); + assertThat(failed.allowPublicJoin()).isEqualTo(original.allowPublicJoin()); + assertThat(failed.entitlementVersion()).isEqualTo(original.entitlementVersion()); + assertThat(failed.entitlementAuthorityAvailability()) + .isEqualTo(bound ? "AVAILABLE" : "NOT_EVALUATED"); + assertThat(failed.lastAttemptFailureCode()).isNull(); + assertThat(failed.membershipId()).isNull(); + assertThat(failed.terminalProof()).isNull(); + String retained = f.bytes(); + var replay = + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure(f.requestId(), f.scope(), f.caller(), outcome)); + assertThat(replay).isEqualTo(failed); + assertThat(f.bytes()).isEqualTo(retained); + f.transaction() + .executeWithoutResult( + status -> + assertThat( + f.operations().insertCanonicalIntent(f.requestId(), f.scope(), f.caller())) + .isFalse()); + if (bound) { + var policyReplay = + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence( + f.requestId(), f.scope(), f.caller(), true, 23)); + assertThat(policyReplay).isEqualTo(failed); + } else { + assertThatThrownBy( + () -> + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence( + f.requestId(), f.scope(), f.caller(), true, 23))) + .isInstanceOf( + AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + } + assertThatThrownBy( + () -> + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), + f.scope(), + f.caller(), + "TENANT_BILLING_BLOCKED"))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThatThrownBy( + () -> + f.transaction() + .execute( + status -> + f.operations() + .recordCanonicalPolicyUnavailable( + f.requestId(), + f.scope(), + f.caller(), + "ENTITLEMENT_UNAVAILABLE"))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThatThrownBy( + () -> + f.dsl() + .execute( + "UPDATE account_join_operations SET updated_at = CURRENT_TIMESTAMP WHERE request_id = ?", + f.requestId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(f.bytes()).isEqualTo(retained); + f.assertNoSuccessEffects(); + } + + @Test + void + boundPendingUnavailableDiagnosticsNeverDowngradePolicyAndExactRecoveryOnlyClearsDiagnostics() { + JournalFixture f = journalFixture(); + var bound = + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence( + f.requestId(), f.scope(), f.caller(), true, 23)); + var unavailable = + f.transaction() + .execute( + status -> + f.operations() + .recordCanonicalPolicyUnavailable( + f.requestId(), f.scope(), f.caller(), "ENTITLEMENT_UNAVAILABLE")); + assertThat(unavailable.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(unavailable.requestDigest()).isEqualTo(bound.requestDigest()); + assertThat(unavailable.entitlementVersion()).isEqualTo(23); + assertThat(unavailable.allowPublicJoin()).isTrue(); + assertThat(unavailable.lastAttemptAuthorityAvailability()).isEqualTo("UNAVAILABLE"); + assertThat(unavailable.lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + var targetUnavailable = + f.transaction() + .execute( + status -> + f.operations() + .recordCanonicalAttemptFailure( + f.requestId(), + f.scope(), + f.caller(), + "NOT_EVALUATED", + "AUTH_UNAVAILABLE")); + assertThat(targetUnavailable.requestDigest()).isEqualTo(bound.requestDigest()); + assertThat(targetUnavailable.lastAttemptFailureCode()).isEqualTo("AUTH_UNAVAILABLE"); + String beforeConflict = f.bytes(); + assertThatThrownBy( + () -> + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence( + f.requestId(), f.scope(), f.caller(), true, 24))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThat(f.bytes()).isEqualTo(beforeConflict); + var recovered = + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence( + f.requestId(), f.scope(), f.caller(), true, 23)); + assertThat(recovered.requestDigest()).isEqualTo(bound.requestDigest()); + assertThat(recovered.entitlementVersion()).isEqualTo(bound.entitlementVersion()); + assertThat(recovered.allowPublicJoin()).isEqualTo(bound.allowPublicJoin()); + assertThat(recovered.lastAttemptAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(recovered.lastAttemptFailureCode()).isNull(); + String recoveredBytes = f.bytes(); + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); + assertThat(f.bytes()).isEqualTo(recoveredBytes); + f.assertNoSuccessEffects(); + } + + @Test + void definitivePublicJoinDenialRetainsItsAlreadyBoundNegativePolicy() { + JournalFixture f = journalFixture(); + var deniedPolicy = + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence( + f.requestId(), f.scope(), f.caller(), false, 23)); + var failed = + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), + f.scope(), + f.caller(), + "PUBLIC_PRODUCTION_ADMISSION_DENIED")); + assertThat(failed.status()).isEqualTo("FAILED"); + assertThat(failed.allowPublicJoin()).isFalse(); + assertThat(failed.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(failed.requestDigest()).isEqualTo(deniedPolicy.requestDigest()); + assertThat(failed.entitlementVersion()).isEqualTo(deniedPolicy.entitlementVersion()); + f.assertNoSuccessEffects(); + } + + @Test + void failedJournalRejectsConflictingCallerRequestAndRetainedScopeWithoutRewritingReceipt() { + JournalFixture f = journalFixture(); + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID")); + String retained = f.bytes(); + var alternate = + canonicalScope("different-canonical-bearer", f.scope().accountId(), f.scope().tenantId()); + f.transaction() + .executeWithoutResult( + status -> + f.scopes() + .insertCanonical( + f.accountId(), alternate, f.read().scopeEvidence().tenantProvenance())); + assertThatThrownBy( + () -> + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), + f.scope(), + "different-caller", + "CONNECT_SCOPE_INVALID"))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThatThrownBy( + () -> + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure( + "different-global-request", + f.scope(), + f.caller(), + "CONNECT_SCOPE_INVALID"))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThatThrownBy( + () -> + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), alternate, f.caller(), "CONNECT_SCOPE_INVALID"))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThat(f.bytes()).isEqualTo(retained); + } + + @Test + void sqlGuardsRefuseRetryableTerminalOutcomesPolicyDowngradeInventedProofAndTerminalMutation() { + JournalFixture f = journalFixture(); + String original = f.bytes(); + for (String change : + java.util.List.of( + "status = 'FAILED', outcome = 'ENTITLEMENT_UNAVAILABLE'", + "status = 'FAILED', outcome = 'CONNECT_SCOPE_INVALID', membership_id = 1", + "status = 'COMMITTED', outcome = 'JOINED'", + "intent_digest = 'sha256:" + "b".repeat(64) + "'")) { + assertThatThrownBy( + () -> + f.dsl() + .execute( + "UPDATE account_join_operations SET " + change + " WHERE request_id = ?", + f.requestId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(f.bytes()).isEqualTo(original); + } + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); + String bound = f.bytes(); + for (String change : + java.util.List.of( + "entitlement_authority_availability = 'UNAVAILABLE'", + "entitlement_version = 24", + "request_digest = NULL", + "last_attempt_authority_availability = 'UNAVAILABLE', last_attempt_failure_code = NULL")) { + assertThatThrownBy( + () -> + f.dsl() + .execute( + "UPDATE account_join_operations SET " + change + " WHERE request_id = ?", + f.requestId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(f.bytes()).isEqualTo(bound); + } + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID")); + String terminal = f.bytes(); + assertThatThrownBy( + () -> + f.dsl() + .execute( + "DELETE FROM account_join_operations WHERE request_id = ?", f.requestId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy(() -> f.dsl().execute("TRUNCATE account_join_operations")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(f.bytes()).isEqualTo(terminal); + f.assertNoSuccessEffects(); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void journalDiagnosticsAndDefinitiveFailureRollBackAsOneTransaction(boolean bound) { + JournalFixture f = journalFixture(); + if (bound) + f.transaction() + .execute( + status -> + f.operations() + .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); + String original = f.bytes(); + assertThatThrownBy( + () -> + f.transaction() + .execute( + status -> { + f.operations() + .recordCanonicalPolicyUnavailable( + f.requestId(), f.scope(), f.caller(), "ENTITLEMENT_UNAVAILABLE"); + f.operations() + .finishCanonicalFailure( + f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID"); + throw new IllegalStateException("controlled canonical journal rollback"); + })) + .hasMessageContaining("controlled canonical journal rollback"); + assertThat(f.bytes()).isEqualTo(original); + var failed = + f.transaction() + .execute( + status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID")); + assertThat(failed.status()).isEqualTo("FAILED"); + f.assertNoSuccessEffects(); + } + + private JournalFixture journalFixture() { + String schema = createSchema("canonical_join_scope_"); + var source = postgres.dataSource(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext setup = DSL.using(source, SQLDialect.POSTGRES); + DSLContext owner = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); + var account = + Objects.requireNonNull( + setup.fetchOne( + "INSERT INTO accounts (username, email, password_hash) VALUES ('journal-player', 'journal@example.test', 'controlled-hash') RETURNING id, account_uuid")); + long privateAccountId = account.get("id", Long.class); + UUID accountId = account.get("account_uuid", UUID.class); + var fresh = new FreshTenantIdentityAssociationRepository(owner, "prod"); + var tenant = freshTenantEvidence(); + transaction.executeWithoutResult(status -> fresh.importVerified(tenant)); + var scopes = + new AccountConnectScopeRepository(owner, mock(AccountTenantIdentityResolver.class), fresh); + var operations = new AccountJoinOperationRepository(owner, scopes); + var scope = canonicalScope(accountId, tenant.canonicalTenantId()); + String requestId = "journal-" + UUID.randomUUID(); + String caller = "controlled-journal-caller"; + transaction.executeWithoutResult( + status -> { + scopes.insertCanonical( + privateAccountId, + scope, + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenant.operationId(), + tenant.evidenceDigest())); + operations.insertCanonicalIntent(requestId, scope, caller); + }); + return new JournalFixture( + setup, transaction, operations, scopes, scope, privateAccountId, requestId, caller); + } + + /** Physical journal storage proof only; supplied caller/scope selectors do not authenticate. */ + private record JournalFixture( + DSLContext dsl, + TransactionTemplate transaction, + AccountJoinOperationRepository operations, + AccountConnectScopeRepository scopes, + CanonicalJoinScopeV2 scope, + long accountId, + String requestId, + String caller) { + private CanonicalJoinOperationEvidence read() { + return Objects.requireNonNull( + transaction.execute( + status -> operations.findCanonicalEvidenceByRequestId(requestId).orElseThrow())); + } + + private String bytes() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT row_to_json(j)::text FROM account_join_operations j WHERE request_id = ?", + requestId)) + .get(0, String.class); + } + + private void assertNoSuccessEffects() { + for (String table : + java.util.List.of( + "account_tenant_membership", + "account_authority_outbox_events", + "account_audit_outbox")) assertThat(dsl.fetchCount(DSL.table(table))).isZero(); + assertThat(read().membershipId()).isNull(); + assertThat(read().terminalProof()).isNull(); + } + } + + private static Flyway accountFlyway( + DriverManagerDataSource dataSource, String schema, String targetVersion) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration", "classpath:db/migration/saga"); + if (targetVersion != null) { + configuration.target(MigrationVersion.fromVersion(targetVersion)); + } + return configuration.load(); + } + + private static List> flywayHistory(DSLContext dsl) { + return dsl.fetch( + "SELECT installed_rank, version, description, type, script, checksum, installed_by, " + + "installed_on, execution_time, success FROM flyway_schema_history " + + "ORDER BY installed_rank") + .intoMaps(); + } + + private static RetainedPhysicalRow retainedPhysicalRow( + DSLContext dsl, String query, Object... bindings) { + Record row = Objects.requireNonNull(dsl.fetchOne(query, bindings)); + return new RetainedPhysicalRow(row.get(0, String.class), row.get(1, String.class)); + } + + private record RetainedPhysicalRow(String rowJson, String xmin) {} + private static long scopeRowCount(DSLContext dsl, String connectScopeId) { return Objects.requireNonNull( dsl.fetchOne( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java new file mode 100644 index 0000000000..2de7e05f08 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java @@ -0,0 +1,1346 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.stripe.exception.StripeException; +import com.stripe.model.StripeObject; +import com.stripe.net.ApiMode; +import com.stripe.net.ApiResource.RequestMethod; +import com.stripe.net.BaseAddress; +import com.stripe.net.RequestOptions; +import com.stripe.net.StripeResponseGetter; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionProvisioner; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.Category; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Disposition; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.ProducerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionProvisioningService; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +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.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; + +/** Actual owner/SDK composition with controlled enrollment publications and provider transport. */ +@Testcontainers(disabledWithoutDocker = true) +class AccountHostingSubscriptionDispatchPostgresIntegrationTest { + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final AtomicLong GAME_ROWS = new AtomicLong(90000); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void upgradeRetainsPriorAttemptOneAndAddsOnlyNonAuthorizingUnknownGuard() { + Fixture f = fixture("1030"); + ProvisioningClaim claim = claim(f, 1); + var before = new java.util.LinkedHashMap>>(); + for (String table : + List.of( + "accounts", + "subscription_create_operations", + "subscription", + "subscription_provisioning_work", + "subscription_provisioning_attempts")) { + before.put( + table, + f.dsl() + .fetch("SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " + table + " t") + .intoMaps()); + } + migrate(f.source(), f.schema(), "1032"); + for (var entry : before.entrySet()) { + assertThat( + f.dsl() + .fetch( + "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " + + entry.getKey() + + " t") + .intoMaps()) + .isEqualTo(entry.getValue()); + } + assertThat( + Objects.requireNonNull( + f.dsl() + .fetchOne( + "SELECT classification FROM subscription_provider_dispatch_claim")) + .get(0, String.class)) + .isEqualTo("PREEXISTING_UNKNOWN"); + var prepared = f.tx().execute(s -> f.owner().prepareProviderDispatch(claim, UUID.randomUUID())); + var read = f.tx().execute(s -> f.owner().readProviderDispatch(prepared)); + assertThat(read.readyForProviderIo()).isTrue(); + assertThat(read.initialCallAllowed()).isFalse(); + } + + @Test + void upgradeRetainsControlledUnclaimedWorkWithoutInventingDispatchHistory() { + Fixture f = fixture("1030"); + // Controlled retained state is inserted directly with the normal SQL guards enabled. The + // existing production claim owner does not commit nonterminal work without its first attempt. + f.tx() + .executeWithoutResult( + s -> + f.dsl() + .execute( + "INSERT INTO subscription_provisioning_work (request_id, subscription_id, phase, row_version, " + + "attempt_count, max_attempts, max_stalled_attempts, lease_millis, backoff_millis, deadline_at, retry_at) " + + "SELECT request_id, subscription_id, 'RECONCILING', 1, 0, 4, 3, 10000, 1000, " + + "created_at + interval '1 hour', created_at FROM subscription_create_operations WHERE request_id = ?", + f.creation().requestId())); + var retained = + f.dsl() + .fetch( + "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM subscription_provisioning_work t") + .intoMaps(); + assertThat(retained).hasSize(1); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isZero(); + + migrate(f.source(), f.schema(), "1032"); + + assertThat( + f.dsl() + .fetch( + "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM subscription_provisioning_work t") + .intoMaps()) + .isEqualTo(retained); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isZero(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isZero(); + var first = claim(f, 1); + assertThat(first.attemptNumber()).isOne(); + f.transport().duringCreate = f.transport()::confirmFirstInvoice; + var result = + (AccountHostingSubscriptionProvisioningService.Committed) + service(f).provision(first, UUID.randomUUID(), UUID.randomUUID()); + assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); + assertThat(f.transport().creates).isOne(); + assertThat( + Objects.requireNonNull( + f.dsl().fetchOne("SELECT * FROM subscription_provider_dispatch_claim")) + .intoMap()) + .containsEntry("classification", "FIRST_DISPATCH") + .containsEntry("first_attempt_id", first.attemptId()) + .containsEntry("first_claimed_row_version", first.subscriptionRowVersion()); + } + + @Test + void upgradeRetainsExpiredFirstClaimAsTerminalWithoutInventingDispatchHistory() { + Fixture f = fixture("1030", Duration.ofSeconds(5)); + awaitDatabaseTime(f, f.creation().createdAt().plusSeconds(5)); + var failed = + f.tx().execute(s -> f.owner().claim(f.creation().requestId(), 1, UUID.randomUUID())); + assertThat(failed.disposition()).isEqualTo(Disposition.TERMINAL_FAILURE); + assertThat(failed.claim()).isNull(); + assertThat( + Objects.requireNonNull(f.dsl().fetchOne("SELECT * FROM subscription_provisioning_work")) + .intoMap()) + .containsEntry("phase", "BILLING_RECONCILIATION_TERMINAL_FAILURE") + .containsEntry("attempt_count", 0) + .containsEntry("failure_reason", "ABSOLUTE_DEADLINE"); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isZero(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isOne(); + var retained = new java.util.LinkedHashMap>>(); + for (String table : + List.of( + "subscription", + "subscription_provisioning_work", + "subscription_provisioning_operator_outbox", + "subscription_instrument_reservations")) { + retained.put( + table, + f.dsl() + .fetch("SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " + table + " t") + .intoMaps()); + } + + migrate(f.source(), f.schema(), "1032"); + + var replay = + f.tx().execute(s -> f.owner().claim(f.creation().requestId(), 1, UUID.randomUUID())); + assertThat(replay.disposition()).isEqualTo(Disposition.TERMINAL_FAILURE); + assertThat(replay.claim()).isNull(); + for (var entry : retained.entrySet()) { + assertThat( + f.dsl() + .fetch( + "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " + + entry.getKey() + + " t") + .intoMaps()) + .isEqualTo(entry.getValue()); + } + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isZero(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isZero(); + assertThat(f.transport().creates).isZero(); + assertThat(f.transport().searches).isZero(); + } + + @Test + void onlyOneFreshInsertionCarriesInitialPermissionAndIndependentReadbackIsMandatory() + throws Exception { + Fixture f = fixture("1032"); + ProvisioningClaim claim = claim(f, 1); + var start = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var first = + executor.submit( + () -> { + start.await(); + return prepareAndRead(f, claim); + }); + var second = + executor.submit( + () -> { + start.await(); + return prepareAndRead(f, claim); + }); + start.countDown(); + var results = List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS)); + assertThat(results) + .extracting(ProviderDispatch::initialCallAllowed) + .containsExactlyInAnyOrder(true, false); + assertThat(prepareAndRead(f, claim).initialCallAllowed()).isFalse(); + } + assertThat(ProviderDispatch.class.getConstructors()).isEmpty(); + } + + @Test + void uncommittedSameTransactionReadbackCannotProduceProviderPermission() { + Fixture f = fixture("1032"); + var claim = claim(f, 1); + assertThatThrownBy( + () -> + f.tx() + .execute( + s -> { + var uncommitted = + f.owner().prepareProviderDispatch(claim, UUID.randomUUID()); + return f.owner().readProviderDispatch(uncommitted); + })) + .hasMessageContaining("new transaction"); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isZero(); + } + + @Test + void expiredExactAttemptReturnsTypedPendingAndReplacedStaleWorkerHitsBindingFence() { + Fixture f = fixture("1032"); + var original = claim(f, 1); + prepareAndRead(f, original); + awaitProvisioningTime(f, "retry_at"); + var before = new java.util.LinkedHashMap>>(); + for (String table : + List.of( + "subscription", + "subscription_provisioning_work", + "subscription_provisioning_attempts", + "subscription_instrument_reservations", + "subscription_provider_dispatch_claim")) { + before.put( + table, + f.dsl() + .fetch("SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " + table + " t") + .intoMaps()); + } + Disposition expired = f.tx().execute(status -> f.owner().deferUnresolved(original)); + assertThat(expired).isEqualTo(Disposition.ATTEMPT_EXPIRED); + for (var entry : before.entrySet()) { + assertThat( + f.dsl() + .fetch( + "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " + + entry.getKey() + + " t") + .intoMaps()) + .isEqualTo(entry.getValue()); + } + var replacement = claim(f, original.subscriptionRowVersion()); + assertThat(replacement.attemptId()).isNotEqualTo(original.attemptId()); + before.replaceAll( + (table, rows) -> + f.dsl() + .fetch( + "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " + table + " t") + .intoMaps()); + // Replacement advanced the subscription version, so the original binding rejects this stale + // worker before the later attempt-identity check can run. + assertThatThrownBy(() -> f.tx().execute(status -> f.owner().deferUnresolved(original))) + .isExactlyInstanceOf(FenceRejectedException.class) + .hasMessage("Pending claim owner/customer/instrument/subscription fence rejected"); + for (var entry : before.entrySet()) { + assertThat( + f.dsl() + .fetch( + "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " + + entry.getKey() + + " t") + .intoMaps()) + .isEqualTo(entry.getValue()); + } + assertThat(f.transport().creates).isZero(); + } + + @Test + void recoveredUndispatchedAttemptMayOwnFirstDispatchButReplayAndExpiredReadbackCannot() { + Fixture f = fixture("1032"); + var first = claim(f, 1); + // Simulate a crash after the worker claim commits but before any dispatch transaction. + awaitProvisioningTime(f, "retry_at"); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isZero(); + assertThat(f.transport().creates).isZero(); + var second = claim(f, first.subscriptionRowVersion()); + assertThat(second.attemptNumber()).isEqualTo(2); + var prepared = + f.tx().execute(s -> f.owner().prepareProviderDispatch(second, UUID.randomUUID())); + assertThat(f.tx().execute(s -> f.owner().readProviderDispatch(prepared)).initialCallAllowed()) + .isTrue(); + assertThat(prepareAndRead(f, second).initialCallAllowed()).isFalse(); + awaitProvisioningTime(f, "lease_expires_at"); + assertThatThrownBy(() -> f.tx().execute(s -> f.owner().readProviderDispatch(prepared))) + .isInstanceOf(FenceRejectedException.class) + .hasMessage("Exact live provisioning claim readback rejected"); + } + + @Test + void expiredUndispatchedFirstClaimRecoversThroughExactlyOneInitialCreate() { + Fixture f = fixture("1032"); + var first = claim(f, 1); + awaitProvisioningTime(f, "retry_at"); + var second = claim(f, first.subscriptionRowVersion()); + f.transport().duringCreate = f.transport()::confirmFirstInvoice; + var result = + (AccountHostingSubscriptionProvisioningService.Committed) + service(f).provision(second, UUID.randomUUID(), UUID.randomUUID()); + assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); + assertThat(result.current().current().subscriptionId()) + .isEqualTo(f.creation().subscriptionId()); + assertThat(f.transport().creates).isEqualTo(1); + var dispatch = + Objects.requireNonNull( + f.dsl().fetchOne("SELECT * FROM subscription_provider_dispatch_claim")); + assertThat(dispatch.get("classification", String.class)).isEqualTo("FIRST_DISPATCH"); + assertThat(dispatch.get("first_attempt_id", UUID.class)).isEqualTo(second.attemptId()); + assertThat(dispatch.get("first_claimed_row_version", Long.class)) + .isEqualTo(second.subscriptionRowVersion()); + } + + @Test + void dispatchIdentityBindingClassificationAndTimeCannotChangeOrDisappear() { + Fixture f = fixture("1032"); + prepareAndRead(f, claim(f, 1)); + var before = f.dsl().fetch("SELECT * FROM subscription_provider_dispatch_claim").intoMaps(); + for (String command : + List.of( + "UPDATE subscription_provider_dispatch_claim SET classification='PREEXISTING_UNKNOWN'", + "UPDATE subscription_provider_dispatch_claim SET recorded_at=recorded_at+interval '1 second'", + "UPDATE subscription_provider_dispatch_claim SET dispatch_id='" + + UUID.randomUUID() + + "'", + "DELETE FROM subscription_provider_dispatch_claim", + "TRUNCATE subscription_provider_dispatch_claim")) { + assertThatThrownBy(() -> f.dsl().execute(command)) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + assertThat(f.dsl().fetch("SELECT * FROM subscription_provider_dispatch_claim").intoMaps()) + .isEqualTo(before); + } + + @Test + void paymentRequiredSdkCreateCannotCommitUntilProviderConfirmsFirstInvoice() { + Fixture f = fixture("1032"); + var first = claim(f, 1); + UUID lifecycleRequest = UUID.randomUUID(); + var pending = + (AccountHostingSubscriptionProvisioningService.Reconciling) + service(f).provision(first, UUID.randomUUID(), lifecycleRequest); + assertThat(pending.transition().outcome()).isEqualTo(Outcome.RECONCILING); + assertThat(pending.transition().reason()).isEqualTo("UNMAPPED_PROVIDER_STATUS"); + assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))).isZero(); + assertThat( + Objects.requireNonNull( + f.dsl() + .fetchOne( + "SELECT status, provider_subscription_id FROM subscription WHERE subscription_id = ?", + f.creation().subscriptionId())) + .intoMap()) + .containsEntry("status", "provisioning") + .containsEntry("provider_subscription_id", null); + assertThat(f.transport().creates).isOne(); + + f.transport().confirmFirstInvoice(); + f.clock().now = f.clock().instant().plusSeconds(1); + var lifecycle = lifecycle(f, new com.stripe.StripeClient(f.transport())); + var transition = + lifecycle.reconcile( + lifecycleRequest, + f.creation().requestId(), + first.subscriptionRowVersion(), + "sub_exact", + first.attemptId()); + assertThat(transition.outcome()).isEqualTo(Outcome.COMMITTED); + var current = lifecycle.readCurrent(f.creation().tenantId()).current(); + assertThat(current.providerSubscriptionId()).isEqualTo("sub_exact"); + assertThat(current.subscriptionId()).isEqualTo(f.creation().subscriptionId()); + assertThat(current.status()).isEqualTo("active"); + assertThat(f.transport().creates).isEqualTo(1); + assertThat(f.transport().subscriptionReads).isGreaterThanOrEqualTo(3); + } + + @Test + void committedTransitionSurvivesUnavailableIndependentReadback() { + Fixture f = fixture("1032"); + f.transport().duringCreate = f.transport()::confirmFirstInvoice; + // The first two reads locate the subscription and supply the lifecycle observation. + f.transport().failSubscriptionRead = 3; + UUID lifecycleRequest = UUID.randomUUID(); + + var result = + (AccountHostingSubscriptionProvisioningService.ReadbackUnavailable) + service(f).provision(claim(f, 1), UUID.randomUUID(), lifecycleRequest); + + assertThat(result.transition().requestId()).isEqualTo(lifecycleRequest); + assertThat(result.transition().outcome()).isEqualTo(Outcome.COMMITTED); + assertThat(f.transport().subscriptionReads).isEqualTo(3); + assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))).isOne(); + + var current = + lifecycle(f, new com.stripe.StripeClient(f.transport())) + .readCurrent(f.creation().tenantId()); + assertThat(current.receiptRequestId()).isEqualTo(lifecycleRequest); + assertThat(current.current().rowVersion()).isEqualTo(result.transition().committedRowVersion()); + assertThat(current.current().providerSubscriptionId()).isEqualTo("sub_exact"); + assertThat(f.transport().creates).isOne(); + } + + @Test + void liveFinalBudgetDispatchSurvivesDisplayRefreshAndCompetingClaim() { + Fixture f = fixture("1032"); + var first = claim(f, 1); + awaitProvisioningTime(f, "retry_at"); + var second = claim(f, first.subscriptionRowVersion()); + awaitProvisioningTime(f, "retry_at"); + var finalClaim = claim(f, second.subscriptionRowVersion()); + assertThat(finalClaim.attemptNumber()).isEqualTo(3); + f.transport().duringCreate = + () -> { + refreshDisplay(f); + var competing = + f.tx() + .execute( + s -> + f.owner() + .claim( + f.creation().requestId(), + finalClaim.subscriptionRowVersion(), + UUID.randomUUID())); + assertThat(competing.disposition()).isEqualTo(Disposition.WAITING); + assertThat(competing.claim()).isNull(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))) + .isZero(); + f.transport().confirmFirstInvoice(); + }; + + var result = + (AccountHostingSubscriptionProvisioningService.Committed) + service(f).provision(finalClaim, UUID.randomUUID(), UUID.randomUUID()); + assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); + assertThat(f.transport().creates).isOne(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isEqualTo(3); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isZero(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))).isOne(); + } + + @Test + void lostCreateResponseRecoversAfterTransientEmptySearchWithoutRecreating() { + Fixture f = fixture("1032"); + f.transport().loseCreateResponse = true; + var first = claim(f, 1); + var lost = + (AccountHostingSubscriptionProvisioningService.Pending) + service(f).provision(first, UUID.randomUUID(), UUID.randomUUID()); + assertThat(lost.disposition()).isEqualTo(Disposition.WAITING); + assertThat(((StripeHostingSubscriptionProvisioner.Pending) lost.providerResult()).reason()) + .isEqualTo("PROVIDER_OUTCOME_UNKNOWN"); + assertThat(f.transport().creates).isEqualTo(1); + f.transport().confirmFirstInvoice(); + f.transport().emptySearchesRemaining = 1; + awaitProvisioningTime(f, "retry_at"); + var second = claim(f, first.subscriptionRowVersion()); + var result = + (AccountHostingSubscriptionProvisioningService.Committed) + service(f).provision(second, UUID.randomUUID(), UUID.randomUUID()); + assertThat(result.current().current().providerSubscriptionId()).isEqualTo("sub_exact"); + assertThat(f.transport().creates).isEqualTo(1); + assertThat(f.transport().searches).isEqualTo(2); + assertThat(f.transport().lists).isEqualTo(1); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isOne(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isZero(); + } + + @Test + void prolongedEmptySearchAfterLostCreateStopsWithOneOperatorItemAndHeldReservation() { + Fixture f = fixture("1032"); + f.transport().loseCreateResponse = true; + var first = claim(f, 1); + var lost = + (AccountHostingSubscriptionProvisioningService.Pending) + service(f).provision(first, UUID.randomUUID(), UUID.randomUUID()); + assertThat(lost.disposition()).isEqualTo(Disposition.WAITING); + assertThat(((StripeHostingSubscriptionProvisioner.Pending) lost.providerResult()).reason()) + .isEqualTo("PROVIDER_OUTCOME_UNKNOWN"); + assertThat(f.transport().exists).isTrue(); + f.transport().emptySearchesRemaining = 2; + f.transport().emptyListsRemaining = 2; + ProvisioningClaim previous = first; + for (int attempt = 2; attempt <= 3; attempt++) { + awaitProvisioningTime(f, "retry_at"); + previous = claim(f, previous.subscriptionRowVersion()); + var pending = + (AccountHostingSubscriptionProvisioningService.Pending) + service(f).provision(previous, UUID.randomUUID(), UUID.randomUUID()); + assertThat(pending.disposition()) + .isEqualTo(attempt == 3 ? Disposition.TERMINAL_FAILURE : Disposition.WAITING); + assertThat(pending.providerResult()) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending("PROVIDER_LOOKUP_UNRESOLVED", null)); + assertThat(f.transport().creates).isEqualTo(1); + } + long finalVersion = previous.subscriptionRowVersion(); + var retry = + Objects.requireNonNull( + f.tx() + .execute( + s -> + f.owner() + .claim(f.creation().requestId(), finalVersion, UUID.randomUUID()))); + assertThat(retry.disposition()).isEqualTo(Disposition.TERMINAL_FAILURE); + assertThat(retry.claim()).isNull(); + assertThat(f.transport().searches).isEqualTo(3); + assertThat(f.transport().lists).isEqualTo(2); + assertThat(f.transport().creates).isEqualTo(1); + var current = + Objects.requireNonNull( + f.dsl() + .fetchOne( + "SELECT status, provider_subscription_id, terminal_resolution_id FROM subscription WHERE subscription_id = ?", + f.creation().subscriptionId())); + assertThat(current.get("status", String.class)).isEqualTo("provisioning"); + assertThat(current.get("provider_subscription_id")).isNull(); + assertThat(current.get("terminal_resolution_id")).isNull(); + assertThat( + Objects.requireNonNull( + f.dsl() + .fetchOne( + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + f.creation().requestId())) + .get("released_at")) + .isNull(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isOne(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_terminal_resolutions"))) + .isZero(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))).isZero(); + assertThat( + Objects.requireNonNull( + f.dsl() + .fetchOne( + "SELECT phase, failure_reason FROM subscription_provisioning_work WHERE request_id = ?", + f.creation().requestId())) + .intoMap()) + .containsEntry("phase", "BILLING_RECONCILIATION_TERMINAL_FAILURE") + .containsEntry("failure_reason", "STALLED_WITHOUT_COMMITTED_PROGRESS"); + } + + @Test + void displayRefreshAfterClaimRefusesDispatchButRetainedWorkReachesOperatorDeadline() { + Fixture f = fixture("1032", Duration.ofSeconds(5)); + var original = claim(f, 1); + var originalRows = f.dsl().fetch("SELECT * FROM subscription_create_operations").intoMaps(); + var reservation = + f.dsl().fetch("SELECT * FROM subscription_instrument_reservations").intoMaps(); + refreshDisplay(f); + + assertThatThrownBy( + () -> + f.tx().execute(s -> f.owner().prepareProviderDispatch(original, UUID.randomUUID()))) + .isInstanceOf(FenceRejectedException.class); + var refused = + (AccountHostingSubscriptionProvisioningService.Pending) + service(f).provision(original, UUID.randomUUID(), UUID.randomUUID()); + assertThat(refused.disposition()).isEqualTo(Disposition.WAITING); + assertThat(refused.providerResult()) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending("DISPATCH_FENCE_REJECTED", null)); + var waiting = + f.tx() + .execute( + s -> + f.owner() + .claim( + f.creation().requestId(), + original.subscriptionRowVersion(), + UUID.randomUUID())); + assertThat(waiting.disposition()).isEqualTo(Disposition.WAITING); + assertThat(waiting.claim()).isNull(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isOne(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isZero(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isZero(); + awaitProvisioningTime(f, "deadline_at"); + + var terminal = + f.tx() + .execute( + s -> + f.owner() + .claim( + f.creation().requestId(), + original.subscriptionRowVersion(), + UUID.randomUUID())); + assertThat(terminal.disposition()).isEqualTo(Disposition.TERMINAL_FAILURE); + assertThat(terminal.claim()).isNull(); + assertThat(f.tx().execute(s -> f.owner().deferUnresolved(original))) + .isEqualTo(Disposition.TERMINAL_FAILURE); + assertThat( + Objects.requireNonNull(f.dsl().fetchOne("SELECT * FROM subscription_provisioning_work")) + .intoMap()) + .containsEntry("phase", "BILLING_RECONCILIATION_TERMINAL_FAILURE") + .containsEntry("failure_reason", "ABSOLUTE_DEADLINE"); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isOne(); + assertThat(f.dsl().fetch("SELECT * FROM subscription_create_operations").intoMaps()) + .usingRecursiveComparison() + .isEqualTo(originalRows); + assertThat(f.dsl().fetch("SELECT * FROM subscription_instrument_reservations").intoMaps()) + .isEqualTo(reservation); + assertThat(Objects.requireNonNull(f.dsl().fetchOne("SELECT * FROM subscription")).intoMap()) + .containsEntry("status", "provisioning") + .containsEntry("provider_subscription_id", null) + .containsEntry("terminal_resolution_id", null); + assertThat(f.transport().creates).isZero(); + assertThat(f.transport().searches).isZero(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_terminal_resolutions"))) + .isZero(); + assertThat(f.dsl().fetchCount(DSL.table("subscription_lifecycle_receipts"))).isZero(); + } + + @Test + void displayRefreshAfterDispatchPreparationRefusesReadbackAndStillAllowsLocalDeadlineFailure() { + Fixture f = fixture("1032", Duration.ofSeconds(5)); + var original = claim(f, 1); + var prepared = + f.tx().execute(s -> f.owner().prepareProviderDispatch(original, UUID.randomUUID())); + var dispatchRows = + f.dsl().fetch("SELECT * FROM subscription_provider_dispatch_claim").intoMaps(); + refreshDisplay(f); + + assertThatThrownBy(() -> f.tx().execute(s -> f.owner().readProviderDispatch(prepared))) + .isInstanceOf(FenceRejectedException.class); + assertThat(f.tx().execute(s -> f.owner().deferUnresolved(original))) + .isEqualTo(Disposition.WAITING); + awaitProvisioningTime(f, "deadline_at"); + assertThat(f.tx().execute(s -> f.owner().deferUnresolved(original))) + .isEqualTo(Disposition.TERMINAL_FAILURE); + assertThat(f.dsl().fetch("SELECT * FROM subscription_provider_dispatch_claim").intoMaps()) + .isEqualTo(dispatchRows); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isOne(); + assertThat(f.transport().creates).isZero(); + } + + @Test + void displayRefreshBeforeInitialClaimRetainsTerminalFailureWithoutDispatch() { + Fixture unclaimed = fixture(null); + refreshDisplay(unclaimed); + var refused = + unclaimed + .tx() + .execute( + s -> + unclaimed + .owner() + .claim(unclaimed.creation().requestId(), 1, UUID.randomUUID())); + assertThat(Objects.requireNonNull(refused).disposition()) + .isEqualTo(Disposition.TERMINAL_FAILURE); + assertThat(refused.claim()).isNull(); + assertThat(unclaimed.dsl().fetchCount(DSL.table("subscription_provisioning_work"))).isOne(); + assertThat( + Objects.requireNonNull( + unclaimed.dsl().fetchOne("SELECT * FROM subscription_provisioning_work")) + .intoMap()) + .containsEntry("phase", "BILLING_RECONCILIATION_TERMINAL_FAILURE") + .containsEntry("failure_reason", "RESERVED_INSTRUMENT_CHANGED"); + assertThat(unclaimed.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))) + .isOne(); + assertThat(unclaimed.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))) + .isZero(); + assertThat(unclaimed.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))) + .isZero(); + assertThat(unclaimed.transport().creates).isZero(); + assertThat(unclaimed.transport().searches).isZero(); + } + + @Test + void displayRefreshDoesNotAuthorizeDirectDispatchInsert() { + Fixture retained = fixture("1032"); + var original = claim(retained, 1); + refreshDisplay(retained); + // Exercise the unchanged V1032 insertion guard independently of the Java eligibility fence. + assertThatThrownBy( + () -> + retained + .tx() + .execute( + s -> + retained + .dsl() + .execute( + "INSERT INTO subscription_provider_dispatch_claim " + + "(creation_request_id, subscription_id, provider_operation_id, dispatch_id, " + + "classification, first_attempt_id, first_claimed_row_version, recorded_at) " + + "VALUES (?, ?, ?, ?, 'FIRST_DISPATCH', ?, ?, ?::timestamptz)", + retained.creation().requestId(), + retained.creation().subscriptionId(), + retained.creation().subscriptionProvisioningRequestId(), + UUID.randomUUID(), + original.attemptId(), + original.subscriptionRowVersion(), + retained.clock().instant().atOffset(ZoneOffset.UTC)))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Provider dispatch lacks exact live original provisioning fence"); + assertThat(retained.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))) + .isZero(); + assertThat(retained.transport().creates).isZero(); + } + + @Test + void displayRefreshDoesNotLetStaleWorkerSettleReplacementOrRewriteOriginalBinding() { + Fixture f = fixture("1032"); + var first = claim(f, 1); + awaitProvisioningTime(f, "retry_at"); + var replacement = claim(f, first.subscriptionRowVersion()); + refreshDisplay(f); + var before = f.dsl().fetch("SELECT * FROM subscription_provisioning_work").intoMaps(); + assertThatThrownBy(() -> f.tx().execute(s -> f.owner().deferUnresolved(first))) + .isInstanceOf(FenceRejectedException.class); + assertThatThrownBy( + () -> + f.tx() + .execute(s -> f.owner().claim(f.creation().requestId(), 1, first.attemptId()))) + .isInstanceOf(FenceRejectedException.class); + assertThat(f.dsl().fetch("SELECT * FROM subscription_provisioning_work").intoMaps()) + .isEqualTo(before); + // Private claims are not caller-constructible. A controlled changed-creation double still must + // not substitute for the immutable retained original during the local settlement readback. + var changedCreation = mock(AccountSubscriptionCreationRecord.class); + when(changedCreation.requestId()).thenReturn(f.creation().requestId()); + var changedClaim = mock(ProvisioningClaim.class); + when(changedClaim.creation()).thenReturn(changedCreation); + when(changedClaim.attemptId()).thenReturn(replacement.attemptId()); + when(changedClaim.subscriptionRowVersion()).thenReturn(replacement.subscriptionRowVersion()); + assertThatThrownBy(() -> f.tx().execute(s -> f.owner().deferUnresolved(changedClaim))) + .isInstanceOf(FenceRejectedException.class) + .hasMessage("Exact retained provisioning settlement claim rejected"); + // The database also retains its existing owner-change guard; this component cannot invent an + // unaudited transfer merely to manufacture a changed-current-owner state. + assertThatThrownBy( + () -> + f.tx() + .execute( + s -> + f.dsl() + .execute( + "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, " + + "owner_generation = ? WHERE tenant_uuid = ?", + UUID.randomUUID(), + f.creation().tenantId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(f.dsl().fetch("SELECT * FROM subscription_provisioning_work").intoMaps()) + .isEqualTo(before); + assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))).isZero(); + assertThat(f.transport().creates).isZero(); + } + + private static void refreshDisplay(Fixture f) { + var instruments = new AccountPaymentInstrumentRepository(f.dsl()); + var original = f.creation(); + var instrument = + instruments + .findByOwner(original.owner().accountUuid(), original.paymentInstrumentId()) + .orElseThrow(); + in( + f.tx(), + () -> + instruments.recordAvailability( + new AccountPaymentInstrumentRepository.AvailabilityObservation( + UUID.randomUUID(), + instrument.instrumentUuid(), + instrument.accountUuid(), + instrument.rowVersion(), + AccountPaymentInstrumentRecord.State.ATTACHABLE, + new AccountPaymentInstrumentRecord.DisplayMetadata("visa", "4242", 12, 2031), + DIGEST))); + } + + private static ProviderDispatch prepareAndRead(Fixture f, ProvisioningClaim claim) { + var prepared = f.tx().execute(s -> f.owner().prepareProviderDispatch(claim, UUID.randomUUID())); + assertThat(prepared.readyForProviderIo()).isFalse(); + assertThat(prepared.initialCallAllowed()).isFalse(); + return f.tx().execute(s -> f.owner().readProviderDispatch(prepared)); + } + + private static ProvisioningClaim claim(Fixture f, long version) { + ProvisioningClaim claim = + Objects.requireNonNull( + f.tx() + .execute( + s -> + f.owner() + .claim(f.creation().requestId(), version, UUID.randomUUID()) + .claim())); + // The controlled provider observation clock follows the real, newly issued DB lease. + f.clock().now = claim.claimedAt(); + return claim; + } + + private static void awaitProvisioningTime(Fixture f, String field) { + if (!List.of("retry_at", "lease_expires_at", "deadline_at").contains(field)) { + throw new IllegalArgumentException("Only retained provisioning deadlines may be awaited"); + } + Instant deadline = + Objects.requireNonNull( + f.dsl() + .fetchOne( + "SELECT " + + field + + " FROM subscription_provisioning_work WHERE request_id = ?", + f.creation().requestId())) + .get(field, OffsetDateTime.class) + .toInstant(); + awaitDatabaseTime(f, deadline); + } + + private static void awaitDatabaseTime(Fixture f, Instant deadline) { + Instant before = + Objects.requireNonNull(f.dsl().fetchOne("SELECT clock_timestamp() AS now")) + .get("now", OffsetDateTime.class) + .toInstant(); + assertThat(Duration.between(before, deadline)).isLessThanOrEqualTo(Duration.ofSeconds(12)); + f.dsl().execute("SELECT pg_sleep_until(?::timestamptz)", deadline.atOffset(ZoneOffset.UTC)); + Instant after = + Objects.requireNonNull(f.dsl().fetchOne("SELECT clock_timestamp() AS now")) + .get("now", OffsetDateTime.class) + .toInstant(); + assertThat(after).isAfterOrEqualTo(deadline); + f.clock().now = after; + } + + private static AccountHostingSubscriptionProvisioningService service(Fixture f) { + var stripe = new com.stripe.StripeClient(f.transport()); + return new AccountHostingSubscriptionProvisioningService( + f.owner(), + new StripeHostingSubscriptionProvisioner( + stripe, f.clock(), false, Duration.ofMillis(250), Duration.ofSeconds(1)), + lifecycle(f, stripe), + new DataSourceTransactionManager(f.source())); + } + + private static AccountHostingSubscriptionLifecycleService lifecycle( + Fixture f, com.stripe.StripeClient stripe) { + return new AccountHostingSubscriptionLifecycleService( + f.owner(), + new StripeHostingSubscriptionObserver( + stripe, f.clock(), Duration.ofMillis(250), Duration.ofSeconds(1)), + new DataSourceTransactionManager(f.source())); + } + + private static Fixture fixture(String target) { + return fixture(target, Duration.ofHours(1)); + } + + private static Fixture fixture(String target, Duration absoluteTimeout) { + String schema = "hosting_dispatch_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + source.setSchema(schema); + migrate(source, schema, target); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setTimeout(10); + var catalog = + new AccountHostingPlanCatalog( + List.of( + new AccountHostingPlanCatalog.ConfiguredPlan( + "hosting", "price_controlled", "1", "100", "2", "1048576"))); + var intents = new AccountSubscriptionIntentRepository(dsl, catalog); + long row = GAME_ROWS.incrementAndGet(); + UUID accountUuid = enroll(dsl, transaction, row); + UUID tenantId = UUID.randomUUID(); + UUID tenantCreateRequest = UUID.randomUUID(); + UUID tenantCreateOperation = UUID.randomUUID(); + String tenantKey = "hosting-fixture-game-" + row; + String tenantRequestDigest = + GameTenantCreationDigest.requestDigest( + "prod", tenantCreateRequest, tenantKey, "Controlled hosting", "Storage only"); + var tenantSource = + new FreshTenantCreationEvidence( + 1, + "prod", + tenantCreateRequest, + tenantCreateOperation, + tenantRequestDigest, + tenantId, + row, + tenantKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", + tenantCreateRequest, + tenantCreateOperation, + tenantRequestDigest, + tenantId, + row, + tenantKey, + "NEW_GAME_ROW")); + in( + transaction, + () -> { + new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(tenantSource); + return new AccountAuthorityGenerationRepository(dsl).initializeTenantIfAbsent(tenantId); + }); + + UUID authorizationOperation = UUID.randomUUID(); + var creator = + new FreshTenantCreatorEvidence( + 1, + tenantSource, + accountUuid, + authorizationOperation, + DIGEST, + FreshTenantCreatorDigest.evidenceDigest( + 1, tenantSource, accountUuid, authorizationOperation, DIGEST)); + var owner = + in( + transaction, + () -> + new AccountInitialTenantBillingOwnerRepository(dsl) + .establishInitial( + new AccountInitialTenantBillingOwnerRepository.InitialRequest( + UUID.randomUUID(), creator, UUID.randomUUID(), 1, true))); + + var customers = new AccountBillingCustomerRepository(dsl); + var pendingCustomer = + in( + transaction, + () -> + customers + .retainIntent(accountUuid, UUID.randomUUID(), UUID.randomUUID()) + .customer()); + var customer = + in( + transaction, + () -> + customers.recordObservation( + accountUuid, + pendingCustomer.customerProvisioningRequestId(), + 1, + UUID.randomUUID(), + AccountBillingCustomerRecord.Observation.CONFIRMED, + "cus_" + row, + DIGEST)); + var instrument = + in( + transaction, + () -> + new AccountPaymentInstrumentRepository(dsl) + .retainAttachment( + new AccountPaymentInstrumentRepository.Attachment( + UUID.randomUUID(), + UUID.randomUUID(), + accountUuid, + customer.customerProvisioningRequestId(), + customer.providerCustomerId(), + "pm_" + row, + AccountPaymentInstrumentRecord.State.ATTACHABLE, + new AccountPaymentInstrumentRecord.DisplayMetadata( + "visa", "4242", 12, 2030), + DIGEST))); + var creation = + in( + transaction, + () -> + intents.retainPending( + new AccountSubscriptionCreateRequest( + UUID.randomUUID(), + tenantId, + new OwnerFence(accountUuid, owner.ownerVersion(), owner.ownerGeneration()), + "hosting", + instrument.instrumentUuid(), + 1, + new ProducerEvidence(accountUuid, UUID.randomUUID(), DIGEST), + null))); + + var clock = new MutableClock(creation.createdAt().plusSeconds(1)); + var lifecycleOwner = + new AccountHostingSubscriptionLifecycleRepository( + dsl, + intents, + clock, + new AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits( + 4, + 3, + absoluteTimeout.compareTo(Duration.ofSeconds(10)) < 0 + ? absoluteTimeout + : Duration.ofSeconds(10), + Duration.ofSeconds(1), + absoluteTimeout), + new AccountHostingSubscriptionLifecyclePolicy( + Duration.ofSeconds(15), + new AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming( + Duration.ofSeconds(60), Duration.ofSeconds(120))), + "prod", + false); + var transport = new Transport(creation, instrument.providerPaymentMethodId(), clock); + return new Fixture( + source, schema, dsl, transaction, creation, lifecycleOwner, clock, transport); + } + + private static UUID enroll(DSLContext dsl, TransactionTemplate tx, long suffix) { + return in( + tx, + () -> { + // Controlled publications stipulate delivery; the actual fresh insertion/certification + // owners + // run normally. These fixtures do not qualify production publisher or protected-mount + // custody. + for (Category category : Category.values()) { + UUID publication = UUID.randomUUID(), + policy = UUID.randomUUID(), + closure = UUID.randomUUID(); + String identity = AccountFreshEnrollmentPolicySource.sourceIdentity(category); + byte[] bytes; + try { + bytes = + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder() + .build() + .writeValueAsString( + Map.of( + "schemaVersion", + "account-fresh-enrollment-policy/v1", + "category", + category.storageValue(), + "sourceIdentity", + identity, + "publicationId", + publication.toString(), + "revision", + "1", + "policyId", + policy.toString(), + "policyRule", + "CERTIFY_NEW_ACTIVE_ACCOUNT", + "closureId", + closure.toString(), + "closureRule", + "EXACT_FRESH_INSERT_ONLY"))); + } catch (java.io.IOException failure) { + throw new IllegalStateException(failure); + } + dsl.execute( + "INSERT INTO account_fresh_enrollment_policy_publications " + + "(publication_id, category, revision, policy_id, closure_id, policy_rule, closure_rule, source_identity, source_root, publication_digest, publication_bytes) " + + "VALUES (?, ?, 1, ?, ?, 'CERTIFY_NEW_ACTIVE_ACCOUNT', 'EXACT_FRESH_INSERT_ONLY', ?, ?, ?, ?)", + publication, + category.storageValue(), + policy, + closure, + identity, + "/controlled-test/owner-protected-mount", + AccountFreshEnrollmentPolicySource.digest(bytes), + bytes); + dsl.execute( + "INSERT INTO account_fresh_enrollment_policy_current (category, publication_id, revision) VALUES (?, ?, 1)", + category.storageValue(), + publication); + } + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var restrictions = + new AccountPlatformRestrictionOperationRepository( + dsl, + generations, + outbox, + new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox), + new AccountPlatformRestrictionBirthRepository(dsl)); + var result = + new AccountFreshEnrollmentRepository( + dsl, + new AccountRepository(dsl), + new AccountFreshEnrollmentPolicyRepository(dsl), + restrictions) + .enroll( + new AccountFreshEnrollmentRequest( + UUID.randomUUID(), + "hosting-" + suffix, + "hosting-" + suffix + "@example.test", + "controlled-password-verifier", + true, + "PASSWORD,EMAIL_OTP")); + return result.accountUuid(); + }); + } + + private static T in(TransactionTemplate tx, java.util.function.Supplier action) { + return Objects.requireNonNull(tx.execute(s -> action.get())); + } + + private static void migrate(DriverManagerDataSource source, String schema, String target) { + var configuration = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration", "classpath:db/migration/saga"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private record Fixture( + DriverManagerDataSource source, + String schema, + DSLContext dsl, + TransactionTemplate tx, + AccountSubscriptionCreationRecord creation, + AccountHostingSubscriptionLifecycleRepository owner, + MutableClock clock, + Transport transport) {} + + private static final class MutableClock extends Clock { + private Instant now; + + private MutableClock(Instant now) { + this.now = now; + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now; + } + } + + private static final class Transport implements StripeResponseGetter { + private final AccountSubscriptionCreationRecord creation; + private final String paymentMethod; + private final Clock clock; + private boolean exists; + private boolean firstInvoiceConfirmed; + private boolean loseCreateResponse; + private Runnable duringCreate; + private int emptySearchesRemaining; + private int emptyListsRemaining; + private int searches; + private int lists; + private int creates; + private int subscriptionReads; + private int failSubscriptionRead; + + private Transport( + AccountSubscriptionCreationRecord creation, String paymentMethod, Clock clock) { + this.creation = creation; + this.paymentMethod = paymentMethod; + this.clock = clock; + } + + @Override + @SuppressWarnings("unchecked") + public T request( + BaseAddress base, + RequestMethod method, + String path, + Map params, + Type type, + RequestOptions options, + ApiMode mode) + throws StripeException { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + String response; + if (path.equals("/v1/customers/" + creation.providerCustomerId())) { + response = + "{\"object\":\"customer\",\"id\":\"" + + creation.providerCustomerId() + + "\",\"livemode\":false,\"deleted\":false,\"metadata\":{\"firemud_metadata_schema_version\":\"1\"," + + "\"firemud_operation_type\":\"customer_provisioning\",\"firemud_operation_id\":\"" + + creation.customerProvisioningRequestId() + + "\",\"firemud_account_id\":\"" + + creation.owner().accountUuid() + + "\"}}"; + } else if (path.equals("/v1/payment_methods/" + paymentMethod)) { + response = + "{\"object\":\"payment_method\",\"id\":\"" + + paymentMethod + + "\",\"customer\":\"" + + creation.providerCustomerId() + + "\",\"livemode\":false,\"type\":\"card\",\"card\":{\"brand\":\"visa\",\"last4\":\"4242\",\"exp_month\":12,\"exp_year\":2030}}"; + } else if (path.equals("/v1/subscriptions/search")) { + searches++; + assertThat(params.get("query").toString()) + .contains( + creation.subscriptionProvisioningRequestId().toString(), + creation.subscriptionId().toString()); + boolean visible = exists && emptySearchesRemaining == 0; + if (emptySearchesRemaining > 0) { + emptySearchesRemaining--; + } + response = + "{\"object\":\"search_result\",\"has_more\":false,\"data\":[" + + (visible ? subscription() : "") + + "]}"; + } else if ("/v1/subscriptions".equals(path) && method == RequestMethod.GET) { + lists++; + assertThat(params) + .containsEntry("customer", creation.providerCustomerId()) + .containsEntry("status", "all"); + boolean visible = exists && emptyListsRemaining == 0; + if (emptyListsRemaining > 0) { + emptyListsRemaining--; + } + response = + "{\"object\":\"list\",\"has_more\":false,\"data\":[" + + (visible ? subscription() : "") + + "]}"; + } else if ("/v1/subscriptions".equals(path) && method == RequestMethod.POST) { + creates++; + exists = true; + assertThat(options.getIdempotencyKey()) + .isEqualTo(creation.subscriptionProvisioningRequestId().toString()); + assertThat(params) + .containsEntry("customer", creation.providerCustomerId()) + .containsEntry("default_payment_method", paymentMethod) + .containsEntry("payment_behavior", "default_incomplete"); + assertThat(params.get("items")) + .isEqualTo( + List.of( + Map.of( + "price", + creation.planQuote().providerPriceId(), + "quantity", + creation.planQuote().providerQuantity()))); + if (duringCreate != null) { + Runnable action = duringCreate; + duringCreate = null; + action.run(); + } + if (loseCreateResponse) { + throw org.mockito.Mockito.mock(StripeException.class); + } + response = subscription("incomplete"); + } else if (path.equals("/v1/subscriptions/sub_exact")) { + subscriptionReads++; + if (subscriptionReads == failSubscriptionRead) { + throw mock(StripeException.class); + } + response = subscription(); + } else { + throw new AssertionError("Unexpected provider path " + path); + } + return (T) com.stripe.net.ApiResource.GSON.fromJson(response, type); + } + + private void confirmFirstInvoice() { + assertThat(exists).isTrue(); + firstInvoiceConfirmed = true; + } + + private String subscription() { + return subscription(firstInvoiceConfirmed ? "active" : "incomplete"); + } + + private String subscription(String status) { + return "{\"object\":\"subscription\",\"id\":\"sub_exact\",\"customer\":\"" + + creation.providerCustomerId() + + "\",\"default_payment_method\":\"" + + paymentMethod + + "\",\"livemode\":false,\"status\":\"" + + status + + "\",\"cancel_at_period_end\":false," + + "\"metadata\":{\"firemud_metadata_schema_version\":\"1\",\"firemud_operation_type\":\"subscription_provisioning\"," + + "\"firemud_operation_id\":\"" + + creation.subscriptionProvisioningRequestId() + + "\",\"firemud_subscription_id\":\"" + + creation.subscriptionId() + + "\"}," + + "\"items\":{\"has_more\":false,\"data\":[{\"id\":\"si_exact\",\"object\":\"subscription_item\",\"subscription\":\"sub_exact\"," + + "\"quantity\":" + + creation.planQuote().providerQuantity() + + ",\"current_period_start\":" + + clock.instant().minusSeconds(5).getEpochSecond() + + ",\"current_period_end\":" + + clock.instant().plusSeconds(3600).getEpochSecond() + + ",\"price\":{\"id\":\"" + + creation.planQuote().providerPriceId() + + "\",\"object\":\"price\"}}]}}"; + } + + @Override + public InputStream requestStream( + BaseAddress base, + RequestMethod method, + String path, + Map params, + RequestOptions options, + ApiMode mode) { + throw new AssertionError("No streaming"); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java new file mode 100644 index 0000000000..da0f3691b3 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java @@ -0,0 +1,1989 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import com.stripe.exception.StripeException; +import com.stripe.model.StripeObject; +import com.stripe.net.ApiMode; +import com.stripe.net.ApiResource.RequestMethod; +import com.stripe.net.BaseAddress; +import com.stripe.net.RequestOptions; +import com.stripe.net.StripeResponseGetter; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.sql.SQLException; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.Status; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.AuthorizedActor; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionTerminalResolution.Request; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.ProducerEvidence; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +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.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual PostgreSQL + actual Stripe SDK over CONTROLLED read-only transport. Creator/consent and + * customer/wallet enrollment are controlled source inputs, not qualification of their live issuers. + * No trigger is disabled, no confirmed SDK value is fabricated, and no remote Stripe call is made. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountHostingSubscriptionLifecyclePostgresIntegrationTest { + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final AtomicLong ROWS = new AtomicLong(10_000); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void actualSdkReadCommitsExactMappingReceiptCanonicalStreamsAndConsistentReaderThenReplays() { + Context c = context("1030"); + Fixture f = fixture(c); + var claim = claim(f); + UUID request = UUID.randomUUID(); + var committed = + f.service() + .reconcile( + request, + f.creation().requestId(), + claim.subscriptionRowVersion(), + f.providerId(), + claim.attemptId()); + assertThat(committed.outcome()).isEqualTo(Outcome.COMMITTED); + assertThat(committed.committedRowVersion()).isEqualTo(4); + var current = f.service().readCurrent(f.creation().tenantId()); + assertThat(current.subscriptionStatus()).isEqualTo(Status.ACTIVE); + assertThat(current.gameplayAvailable()).isTrue(); + assertThat(current.allowPublicJoin()).isTrue(); + assertThat(current.current().planQuote()).isEqualTo(f.creation().planQuote()); + assertThat(current.current().providerSubscriptionId()).isEqualTo(f.providerId()); + assertThat(current.entitlementVersion()).isOne(); + assertThat(current.tenantBillingSequence()).isOne(); + assertThat(current.tenantAuthorityEvent().tenantBillingSequence()) + .isEqualTo(current.tenantBillingSequence()); + assertThat(current.tenantAuthorityEvent().tenantBillingEventDigest()) + .isEqualTo(current.billingEventDigest()); + var source = + one( + c, + "SELECT * FROM account_tenant_authority_source_records WHERE tenant_uuid = ?", + f.creation().tenantId()); + assertThat(source.get("last_request_id", UUID.class)).isEqualTo(request); + assertThat(source.get("current_generation", Long.class)).isEqualTo(2); + assertThat( + one( + c, + "SELECT o.recorded_transaction_id = r.committed_transaction_id AS same_transaction " + + "FROM subscription_lifecycle_observations o JOIN subscription_lifecycle_receipts r USING (attempt_id) WHERE r.request_id = ?", + request) + .get("same_transaction", Boolean.class)) + .isTrue(); + assertThat( + one( + c, + "SELECT phase FROM subscription_provisioning_work WHERE request_id = ?", + f.creation().requestId()) + .get("phase", String.class)) + .isEqualTo("CONFIRMED"); + assertThat(count(c, "subscription_provider_history")).isOne(); + assertThat(count(c, "account_demo_tenant_entitlements")).isZero(); + int reads = f.transport().reads; + assertThat( + f.service() + .reconcile(request, f.creation().requestId(), 2, f.providerId(), claim.attemptId())) + .isEqualTo(committed); + assertThat(f.transport().reads).isEqualTo(reads); + assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); + assertThat(count(c, "account_tenant_entitlement_outbox_events")).isOne(); + assertThat(count(c, "account_authority_outbox_events")).isOne(); + assertThatThrownBy( + () -> + f.service() + .reconcile( + request, f.creation().requestId(), 2, "sub_other", claim.attemptId())) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThat(f.transport().reads).isEqualTo(reads); + } + + @Test + void trialUsesRetainedQuoteWithoutTodaysCatalogAndSqlShapedRowsAloneNeverAuthorize() { + Context c = context("1030"); + Fixture f = fixture(c); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + assertThat(f.transport().reads).isZero(); + f.transport().json = response(f, "trialing"); + var emptyCatalogRepository = + new AccountSubscriptionIntentRepository(c.dsl(), new AccountHostingPlanCatalog(List.of())); + var owner = owner(c, f.clock(), emptyCatalogRepository); + var service = service(c, owner, f.transport(), f.clock()); + var claim = service.claimProvisioning(f.creation().requestId(), 1, UUID.randomUUID()).claim(); + assertThat( + service + .reconcile( + UUID.randomUUID(), + f.creation().requestId(), + 2, + f.providerId(), + claim.attemptId()) + .outcome()) + .isEqualTo(Outcome.COMMITTED); + assertThat(service.readCurrent(f.creation().tenantId()).subscriptionStatus()) + .isEqualTo(Status.TRIALING); + assertThat(service.readCurrent(f.creation().tenantId()).current().planQuote()) + .isEqualTo(f.creation().planQuote()); + assertSqlState( + "23514", + () -> c.setup().execute("UPDATE subscription_lifecycle_receipts SET status = 'active'")); + assertSqlState( + "23514", + () -> + c.setup().execute("UPDATE subscription_lifecycle_observations SET payload = payload")); + assertSqlState( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription SET plan_quote_digest = ?, row_version = row_version + 1 WHERE subscription_id = ?", + "sha256:" + "f".repeat(64), + f.creation().subscriptionId())); + assertSqlState( + "23514", + () -> + c.setup() + .execute( + "UPDATE billing_customer SET provider_customer_id = 'cus_wrong', row_version = row_version + 1 WHERE account_uuid = ?", + f.creation().owner().accountUuid())); + } + + @Test + void rawSqlActiveMappingWithoutGenuineClaimAndReceiptCannotBecomeAReadOrLifecycleSource() { + Context c = context("1030"); + Fixture f = fixture(c); + c.tx() + .executeWithoutResult( + s -> { + c.dsl() + .execute( + "INSERT INTO subscription_provider_history (provider_subscription_id, subscription_id, operation_kind, request_id, " + + "provider_operation_id, role, effective_at, evidence_digest) VALUES (?, ?, 'SUBSCRIPTION_PROVISIONING', ?, ?, 'canonical', ?::timestamptz, ?)", + f.providerId(), + f.creation().subscriptionId(), + f.creation().requestId(), + f.creation().subscriptionProvisioningRequestId(), + f.clock().instant().atOffset(ZoneOffset.UTC), + DIGEST); + c.dsl() + .execute( + "UPDATE subscription SET status = 'active', provider_subscription_id = ?, row_version = row_version + 1 WHERE subscription_id = ?", + f.providerId(), + f.creation().subscriptionId()); + }); + assertThat(c.intents().findCurrentByTenant(f.creation().tenantId()).orElseThrow().status()) + .isEqualTo("active"); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + assertThatThrownBy( + () -> + f.service() + .reconcile( + UUID.randomUUID(), f.creation().requestId(), 2, f.providerId(), null)) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); + assertThat(f.transport().reads).isZero(); + assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); + assertThat(count(c, "account_tenant_authority_source_records")).isZero(); + } + + @Test + void hostingExtendsExistingDemoStreamsWithoutRewritingOrReinterpretingDemoEvidence() { + Context c = context("1030"); + Fixture f = fixture(c); + var identity = new FreshTenantIdentityAssociationRepository(c.dsl(), "prod"); + var generations = new AccountAuthorityGenerationRepository(c.dsl()); + var billing = new AccountTenantEntitlementOutboxRepository(c.dsl()); + var events = + new AccountTenantAuthorityEventRepository( + c.dsl(), new AccountAuthorityOutboxRepository(c.dsl()), billing, identity, generations); + var demo = + new AccountDemoTenantEntitlementRepository(c.dsl(), identity, generations, billing, events); + var source = in(c, () -> identity.read(f.creation().tenantId()).orElseThrow()); + var demoRequest = + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + source.canonicalTenantId(), + source.creationRequestId(), + source.requestDigest(), + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(5, 1, 1024)); + in(c, () -> demo.provision(demoRequest, source)); + var demoRow = + one( + c, + "SELECT row_to_json(e)::text AS value, xmin::text AS xmin FROM account_demo_tenant_entitlements e WHERE tenant_uuid = ?", + source.canonicalTenantId()); + byte[] demoEvent = + one( + c, + "SELECT payload FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = 1", + source.canonicalTenantId()) + .get("payload", byte[].class); + activate(f); + var current = f.service().readCurrent(source.canonicalTenantId()); + assertThat(current.entitlementVersion()).isEqualTo(2); + assertThat(current.tenantBillingSequence()).isEqualTo(2); + assertThat(current.tenantAuthorityEvent().tenantAuthorityGeneration()).isEqualTo(3); + assertThat(current.subscriptionStatus()).isEqualTo(Status.ACTIVE); + assertThat( + one( + c, + "SELECT row_to_json(e)::text AS value, xmin::text AS xmin FROM account_demo_tenant_entitlements e WHERE tenant_uuid = ?", + source.canonicalTenantId())) + .isEqualTo(demoRow); + assertThat( + one( + c, + "SELECT payload FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = 1", + source.canonicalTenantId()) + .get("payload", byte[].class)) + .isEqualTo(demoEvent); + assertThat(count(c, "account_tenant_entitlement_outbox_streams")).isOne(); + assertThat(count(c, "account_authority_outbox_streams")).isOne(); + assertThat(count(c, "account_tenant_authority_source_records")).isOne(); + } + + @Test + void concurrentSameRequestObservesOneInflightOwnerAndReplaysOneCommittedTransition() + throws Exception { + Context c = context("1030"); + Fixture f = fixture(c); + var claim = claim(f); + UUID request = UUID.randomUUID(); + CountDownLatch reading = new CountDownLatch(1); + CountDownLatch completeRead = new CountDownLatch(1); + f.transport().duringRead = + () -> { + reading.countDown(); + await(completeRead); + }; + var executor = Executors.newSingleThreadExecutor(); + try { + var winner = + executor.submit( + () -> + f.service() + .reconcile( + request, f.creation().requestId(), 2, f.providerId(), claim.attemptId())); + assertThat(reading.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat( + f.service() + .reconcile( + request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) + .outcome()) + .isEqualTo(Outcome.RECONCILING); + completeRead.countDown(); + var committed = winner.get(10, TimeUnit.SECONDS); + assertThat(committed.outcome()).isEqualTo(Outcome.COMMITTED); + assertThat( + f.service() + .reconcile( + request, f.creation().requestId(), 2, f.providerId(), claim.attemptId())) + .isEqualTo(committed); + assertThat(f.transport().reads).isOne(); + assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); + assertThat(count(c, "subscription_provider_history")).isOne(); + } finally { + completeRead.countDown(); + executor.shutdownNow(); + } + } + + @Test + void providerIdMetadataCustomerInstrumentPriceQuantityAndUnknownStatusesCannotBecomeAuthority() { + Context c = context("1030"); + for (String mismatch : + List.of("id", "metadata", "customer", "instrument", "price", "quantity", "unknown")) { + Fixture f = fixture(c); + var claim = claim(f); + String json = response(f, "active"); + f.transport().json = + switch (mismatch) { + case "id" -> json.replace(f.providerId(), "sub_wrong"); + case "metadata" -> + json.replace( + f.creation().subscriptionProvisioningRequestId().toString(), + UUID.randomUUID().toString()); + case "customer" -> json.replace(f.creation().providerCustomerId(), "cus_wrong"); + case "instrument" -> json.replace(f.instrument().providerPaymentMethodId(), "pm_wrong"); + case "price" -> json.replace(f.creation().planQuote().providerPriceId(), "price_wrong"); + case "quantity" -> json.replace("\"quantity\":1", "\"quantity\":2"); + default -> json.replace("\"active\"", "\"unrecognized_status\""); + }; + UUID request = UUID.randomUUID(); + assertThat( + f.service() + .reconcile( + request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) + .outcome()) + .as(mismatch) + .isEqualTo(Outcome.RECONCILING); + assertThat( + one( + c, + "SELECT state FROM subscription_lifecycle_operations WHERE request_id = ?", + request) + .get("state", String.class)) + .isEqualTo("PENDING"); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + assertThat( + one( + c, + "SELECT provider_subscription_id FROM subscription WHERE subscription_id = ?", + f.creation().subscriptionId()) + .get("provider_subscription_id")) + .isNull(); + } + assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); + assertThat(count(c, "subscription_provider_history")).isZero(); + assertThat(count(c, "account_tenant_entitlement_outbox_events")).isZero(); + } + + @Test + void providerExceptionIsNotAbsenceAndSameRequestRecoversWithoutAnotherProviderIdentity() { + Context c = context("1030"); + Fixture f = fixture(c); + var claim = claim(f); + UUID request = UUID.randomUUID(); + f.transport().failure = mock(StripeException.class); + assertThat( + f.service() + .reconcile(request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) + .outcome()) + .isEqualTo(Outcome.RECONCILING); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); + assertThat( + one( + c, + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + f.creation().requestId()) + .get("released_at")) + .isNull(); + f.transport().failure = null; + f.clock().advance(Duration.ofSeconds(2)); + assertThat( + f.service() + .reconcile(request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) + .outcome()) + .isEqualTo(Outcome.COMMITTED); + assertThat(count(c, "subscription_create_operations")).isOne(); + assertThat(count(c, "subscription_create_provider_identities")).isEqualTo(2); + assertThat(count(c, "subscription_lifecycle_attempts")).isEqualTo(2); + assertThat(f.service().readCurrent(f.creation().tenantId()).allowPublicJoin()).isTrue(); + } + + @Test + void walletDisplayAdvanceDuringSdkReadPreservesBindingAndStaleRowOwnerInputsRejectBeforeRead() { + Context c = context("1030"); + Fixture f = fixture(c); + var claim = claim(f); + assertThatThrownBy( + () -> + f.service() + .reconcile( + UUID.randomUUID(), + f.creation().requestId(), + 1, + f.providerId(), + claim.attemptId())) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); + assertThat(f.transport().reads).isZero(); + var wrongOwner = + new AccountSubscriptionCreateRequest( + UUID.randomUUID(), + f.creation().tenantId(), + new OwnerFence( + f.creation().owner().accountUuid(), + f.creation().owner().version() + 1, + UUID.randomUUID()), + f.creation().planCode(), + f.creation().paymentInstrumentId(), + f.creation().reservedInstrumentVersion(), + new ProducerEvidence(f.creation().owner().accountUuid(), UUID.randomUUID(), DIGEST), + null); + assertThatThrownBy(() -> c.tx().execute(s -> c.intents().retainPending(wrongOwner))) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); + f.transport().duringRead = + () -> + in( + c, + () -> + new AccountPaymentInstrumentRepository(c.dsl()) + .recordAvailability( + new AccountPaymentInstrumentRepository.AvailabilityObservation( + UUID.randomUUID(), + f.instrument().instrumentUuid(), + f.creation().owner().accountUuid(), + 1L, + AccountPaymentInstrumentRecord.State.ATTACHABLE, + new AccountPaymentInstrumentRecord.DisplayMetadata( + "visa", "4242", 12, 2031), + DIGEST))); + assertThat( + f.service() + .reconcile( + UUID.randomUUID(), + f.creation().requestId(), + 2, + f.providerId(), + claim.attemptId()) + .outcome()) + .isEqualTo(Outcome.COMMITTED); + assertThat( + new AccountPaymentInstrumentRepository(c.dsl()) + .findByOwner(f.creation().owner().accountUuid(), f.instrument().instrumentUuid()) + .orElseThrow() + .rowVersion()) + .isEqualTo(2L); + assertThat( + c.intents() + .findCurrentByTenant(f.creation().tenantId()) + .orElseThrow() + .reservedInstrumentVersion()) + .isEqualTo(1L); + assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); + assertThat(count(c, "account_tenant_entitlement_outbox_events")).isOne(); + assertThat(count(c, "account_tenant_authority_source_records")).isOne(); + assertThat(f.service().readCurrent(f.creation().tenantId()).subscriptionStatus()) + .isEqualTo(Status.ACTIVE); + } + + @Test + void + deferredSqlFailureRollsBackMappingObservationReceiptGenerationAndBothEventsThenRetryRecovers() { + Context c = context("1030"); + Fixture f = fixture(c); + var claim = claim(f); + UUID request = UUID.randomUUID(); + var prepared = + in( + c, + () -> + f.owner() + .prepare( + request, f.creation().requestId(), 2, f.providerId(), claim.attemptId())); + var actualSdk = f.observer().observe(prepared.binding()); + assertSqlState( + "23514", + () -> + c.tx() + .executeWithoutResult( + s -> { + assertThat(f.owner().apply(prepared, actualSdk).outcome()) + .isEqualTo(Outcome.COMMITTED); + var sameTransactionFence = + f.owner().prepareCurrentRead(f.creation().tenantId()); + assertThat( + f.owner() + .readCurrent(sameTransactionFence, actualSdk) + .allowPublicJoin()) + .isTrue(); + // A real monotonic generation advance without its source event must fail at + // transaction + // completion, after the lifecycle owner's ordinary writes and exact readback + // have executed. + c.dsl() + .execute( + "UPDATE account_authority_generations SET generation = generation + 1, source_version = source_version + 1 " + + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + f.creation().tenantId()); + })); + for (String table : + List.of( + "subscription_provider_history", + "subscription_lifecycle_observations", + "subscription_lifecycle_receipts", + "account_tenant_entitlement_outbox_events", + "account_authority_outbox_events", + "account_tenant_authority_source_records")) { + assertThat(count(c, table)).as(table).isZero(); + } + assertThat( + one( + c, + "SELECT generation FROM account_authority_generations WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + f.creation().tenantId()) + .get("generation", Long.class)) + .isOne(); + assertThat( + one( + c, + "SELECT state FROM subscription_lifecycle_operations WHERE request_id = ?", + request) + .get("state", String.class)) + .isEqualTo("PENDING"); + f.clock().advance(Duration.ofSeconds(12)); + assertThat( + f.service() + .reconcile(request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) + .outcome()) + .isEqualTo(Outcome.COMMITTED); + assertThat(f.service().readCurrent(f.creation().tenantId()).tenantBillingSequence()).isOne(); + } + + @Test + void databaseGuardRejectsUnauditedOwnerUpdateDuringSdkTransport() { + Context c = context("1030"); + Fixture f = fixture(c); + var claim = claim(f); + // The actual database refuses an unaudited transfer. Preserve that guard rather than + // manufacturing an owner change that this source boundary cannot legitimately produce. + f.transport().duringRead = + () -> + c.tx() + .executeWithoutResult( + s -> + c.dsl() + .execute( + "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, owner_generation = ? WHERE tenant_uuid = ?", + UUID.randomUUID(), + f.creation().tenantId())); + UUID reconciliationRequest = UUID.randomUUID(); + assertSqlState( + "23514", + () -> + f.service() + .reconcile( + reconciliationRequest, + f.creation().requestId(), + 2, + f.providerId(), + claim.attemptId())); + assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); + assertThat(count(c, "subscription_provider_history")).isZero(); + assertThat(count(c, "account_authority_outbox_events")).isZero(); + assertThat( + one( + c, + "SELECT state FROM subscription_lifecycle_operations WHERE request_id = ?", + reconciliationRequest) + .get("state", String.class)) + .isEqualTo("PENDING"); + assertThat( + one( + c, + "SELECT lifecycle_inflight_request_id FROM subscription WHERE subscription_id = ?", + f.creation().subscriptionId()) + .get("lifecycle_inflight_request_id", UUID.class)) + .isEqualTo(reconciliationRequest); + assertThat( + one( + c, + "SELECT current_receipt_request_id FROM subscription WHERE subscription_id = ?", + f.creation().subscriptionId()) + .get("current_receipt_request_id", UUID.class)) + .isNull(); + assertThat( + one( + c, + "SELECT owner_version FROM account_tenant_billing_owners WHERE tenant_uuid = ?", + f.creation().tenantId()) + .get("owner_version", Long.class)) + .isEqualTo(f.creation().owner().version()); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + } + + @Test + void realInitialCanceledEvidenceRetiresOnlyItsHoldAndCommittedReceiptCannotBeDetached() { + Context c = context("1030"); + Fixture f = fixture(c); + f.transport().json = response(f, "canceled"); + var claim = claim(f); + assertThat( + f.service() + .reconcile( + UUID.randomUUID(), + f.creation().requestId(), + 2, + f.providerId(), + claim.attemptId()) + .outcome()) + .isEqualTo(Outcome.COMMITTED); + assertThat(f.service().readCurrent(f.creation().tenantId()).gameplayAvailable()).isFalse(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isOne(); + assertThat( + one( + c, + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + f.creation().requestId()) + .get("released_at")) + .isNotNull(); + assertSqlState( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription SET current_receipt_request_id = NULL, row_version = row_version + 1 WHERE subscription_id = ?", + f.creation().subscriptionId())); + assertThat(f.service().readCurrent(f.creation().tenantId()).subscriptionStatus()) + .isEqualTo(Status.CANCELED); + } + + @Test + void freshReadsBeyondObservationAgePreserveCommittedReceiptAndAuthorityUntilRealPeriodEnd() { + for (String status : List.of("active", "trialing")) { + Context c = context("1030"); + Fixture f = fixture(c); + f.transport().json = response(f, status); + activate(f); + var receipt = + one( + c, + "SELECT row_to_json(r)::text AS value, xmin::text AS xmin FROM subscription_lifecycle_receipts r"); + var authority = + one( + c, + "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_tenant_authority_source_records a"); + Instant periodEnd = Instant.ofEpochSecond(f.creation().createdAt().getEpochSecond() + 3600); + assertThat( + one(c, "SELECT valid_until FROM subscription_lifecycle_receipts") + .get(0, java.time.OffsetDateTime.class) + .toInstant()) + .isEqualTo(periodEnd); + int reads = f.transport().reads; + for (int laterRead = 1; laterRead <= 2; laterRead++) { + f.clock().advance(Duration.ofSeconds(30)); + var current = f.service().readCurrent(f.creation().tenantId()); + assertThat(current.gameplayAvailable()).isTrue(); + assertThat(current.validUntil()).isEqualTo(f.clock().instant().plusSeconds(15)); + assertThat(current.tenantBillingSequence()).isOne(); + assertThat(current.tenantAuthorityEvent().tenantAuthorityGeneration()).isEqualTo(2); + assertThat(f.transport().reads).isEqualTo(reads + laterRead); + assertThat( + one( + c, + "SELECT row_to_json(r)::text AS value, xmin::text AS xmin FROM subscription_lifecycle_receipts r")) + .isEqualTo(receipt); + assertThat( + one( + c, + "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_tenant_authority_source_records a")) + .isEqualTo(authority); + assertThat(count(c, "account_tenant_entitlement_outbox_events")).isOne(); + assertThat(count(c, "account_authority_outbox_events")).isOne(); + } + f.clock().advance(Duration.between(f.clock().instant(), periodEnd)); + int beforeExpiredRead = f.transport().reads; + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .isInstanceOf( + AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException.class) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE") + .cause() + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class) + .hasMessageContaining("current receipt is expired"); + assertThat(f.transport().reads).isEqualTo(beforeExpiredRead); + assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); + } + } + + @Test + void canceledReceiptsReturnFreshNegativeProjectionAfterOriginalObservationAgeWithoutMutation() { + for (boolean providerCanceled : new boolean[] {true, false}) { + Context c = context("1030"); + Fixture f = fixture(c); + f.transport().json = + providerCanceled + ? response(f, "canceled") + : response(f, "active") + .replace( + "\"cancel_at\":null", + "\"cancel_at\":" + f.clock().instant().getEpochSecond()); + String originalFacts = f.transport().json; + activate(f); + var receipt = + one( + c, + "SELECT row_to_json(r)::text AS value, xmin::text AS xmin FROM subscription_lifecycle_receipts r"); + var authority = + one( + c, + "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_tenant_authority_source_records a"); + for (int laterRead = 0; laterRead < 2; laterRead++) { + f.clock().advance(Duration.ofSeconds(30)); + var canceled = f.service().readCurrent(f.creation().tenantId()); + assertThat(canceled.subscriptionStatus()).isEqualTo(Status.CANCELED); + assertThat(canceled.gameplayAvailable()).isFalse(); + assertThat(canceled.allowPublicJoin()).isFalse(); + assertThat(canceled.allowNewGameplayBindings()).isFalse(); + assertThat(canceled.allowNewInstanceStarts()).isFalse(); + assertThat(canceled.validUntil()).isEqualTo(f.clock().instant().plusSeconds(15)); + assertThat(canceled.tenantBillingSequence()).isOne(); + } + // An aged terminal receipt is not permission to turn unknown or changed facts into denial. + f.transport().duringRead = () -> f.clock().advance(Duration.ofSeconds(15)); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .isInstanceOf( + AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException.class); + f.transport().json = response(f, "active"); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .isInstanceOf( + AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException.class); + f.transport().json = originalFacts; + assertThat(f.service().readCurrent(f.creation().tenantId()).gameplayAvailable()).isFalse(); + assertThat( + one( + c, + "SELECT row_to_json(r)::text AS value, xmin::text AS xmin FROM subscription_lifecycle_receipts r")) + .isEqualTo(receipt); + assertThat( + one( + c, + "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_tenant_authority_source_records a")) + .isEqualTo(authority); + assertThat(count(c, "account_tenant_entitlement_outbox_events")).isOne(); + assertThat(count(c, "account_authority_outbox_events")).isOne(); + assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); + assertThat(count(c, "subscription_provider_terminal_resolutions")) + .isEqualTo(providerCanceled ? 1 : 0); + } + } + + @Test + void inFlightAndStaleObservationOrChangedSdkFactsNeverRefreshAnOldPositiveSnapshot() { + Context c = context("1030"); + Fixture f = fixture(c); + activate(f); + var fence = in(c, () -> f.owner().prepareCurrentRead(f.creation().tenantId())); + f.transport().json = response(f, "past_due"); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + f.transport().json = response(f, "active"); + f.clock().advance(Duration.ofSeconds(15)); + assertThat(f.service().readCurrent(f.creation().tenantId()).allowPublicJoin()).isTrue(); + f.transport().duringRead = () -> f.clock().advance(Duration.ofSeconds(15)); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + assertThat(f.service().readCurrent(f.creation().tenantId()).allowPublicJoin()).isTrue(); + assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); + assertThat(count(c, "account_tenant_entitlement_outbox_events")).isOne(); + assertThat(count(c, "account_authority_outbox_events")).isOne(); + long currentVersion = + c.intents().findCurrentByTenant(f.creation().tenantId()).orElseThrow().rowVersion(); + var prepared = + in( + c, + () -> + f.owner() + .prepare( + UUID.randomUUID(), + f.creation().requestId(), + currentVersion, + f.providerId(), + null)); + var actualSdk = f.observer().observe(prepared.binding()); + assertThatThrownBy(() -> in(c, () -> f.owner().readCurrent(fence, actualSdk))) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + in(c, () -> f.owner().apply(prepared, actualSdk)); + assertThat(f.service().readCurrent(f.creation().tenantId()).tenantBillingSequence()) + .isEqualTo(2); + } + + @Test + void unchangedInvalidEvidenceExhaustsFrozenStallBudgetOnceAndNeverReleasesBillingWork() { + Context c = context("1030"); + Fixture f = fixture(c); + var claim = claim(f); + UUID request = UUID.randomUUID(); + f.transport().json = response(f, "active").replace("price_controlled", "price_wrong"); + for (int attempt = 1; attempt <= 3; attempt++) { + var outcome = + f.service() + .reconcile(request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) + .outcome(); + assertThat(outcome).isEqualTo(attempt == 3 ? Outcome.TERMINAL_FAILURE : Outcome.RECONCILING); + f.clock().advance(Duration.ofSeconds(2)); + } + int reads = f.transport().reads; + assertThat( + f.service() + .reconcile(request, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) + .outcome()) + .isEqualTo(Outcome.TERMINAL_FAILURE); + assertThat(f.transport().reads).isEqualTo(reads); + assertThat(count(c, "subscription_lifecycle_operator_outbox")).isOne(); + assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); + assertThat( + one( + c, + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + f.creation().requestId()) + .get("released_at")) + .isNull(); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + } + + @Test + void firstPastDueObservationWithoutRetainedRecoveryOriginStaysUnresolvedAndHoldsReservation() { + Context c = context("1030"); + Fixture f = fixture(c); + activate(f); + var receipt = + one( + c, + "SELECT row_to_json(r)::text AS value, xmin::text AS xmin, past_due_since FROM subscription_lifecycle_receipts r"); + assertThat(receipt.get("past_due_since")).isNull(); + var authority = + one( + c, + "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_tenant_authority_source_records a"); + var generations = + c.setup() + .fetch( + "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_authority_generations a") + .intoMaps(); + long version = + c.intents().findCurrentByTenant(f.creation().tenantId()).orElseThrow().rowVersion(); + UUID request = UUID.randomUUID(); + f.transport().json = response(f, "past_due"); + var unresolved = + f.service().reconcile(request, f.creation().requestId(), version, f.providerId(), null); + assertThat(unresolved.requestId()).isEqualTo(request); + assertThat(unresolved.outcome()).isEqualTo(Outcome.RECONCILING); + assertThat(unresolved.reason()).isEqualTo("RECOVERY_ORIGIN_UNRESOLVED"); + assertThat(unresolved.committedRowVersion()).isZero(); + var pending = + one( + c, + "SELECT state, failure_reason FROM subscription_lifecycle_operations WHERE request_id = ?", + request); + assertThat(pending.get("state", String.class)).isEqualTo("PENDING"); + assertThat(pending.get("failure_reason", String.class)).isEqualTo("RECOVERY_ORIGIN_UNRESOLVED"); + var observation = + one( + c, + "SELECT raw_status, mapping_reason FROM subscription_lifecycle_observations WHERE request_id = ?", + request); + assertThat(observation.get("raw_status", String.class)).isEqualTo("past_due"); + assertThat(observation.get("mapping_reason", String.class)) + .isEqualTo("RECOVERY_ORIGIN_UNRESOLVED"); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .isInstanceOf( + AccountHostingSubscriptionLifecycleService.EntitlementUnavailableException.class); + assertThat( + one( + c, + "SELECT row_to_json(r)::text AS value, xmin::text AS xmin, past_due_since FROM subscription_lifecycle_receipts r")) + .isEqualTo(receipt); + assertThat( + one( + c, + "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_tenant_authority_source_records a")) + .isEqualTo(authority); + assertThat( + c.setup() + .fetch( + "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM account_authority_generations a") + .intoMaps()) + .isEqualTo(generations); + assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); + assertThat(count(c, "account_tenant_entitlement_outbox_events")).isOne(); + assertThat(count(c, "account_authority_outbox_events")).isOne(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); + assertThat( + one( + c, + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + f.creation().requestId()) + .get("released_at")) + .isNull(); + } + + @Test + void effectiveCancellationAdvancesMonotonicCutoffWithoutPrematureReservationRelease() { + Context c = context("1030"); + Fixture f = fixture(c); + activate(f); + Instant cancellation = + Instant.ofEpochSecond(f.clock().instant().plusSeconds(2).getEpochSecond()); + f.transport().json = + response(f, "active") + .replace("\"cancel_at\":null", "\"cancel_at\":" + cancellation.getEpochSecond()); + refresh(f); + f.clock().advance(Duration.between(f.clock().instant(), cancellation)); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + refresh(f); + var canceled = f.service().readCurrent(f.creation().tenantId()); + assertThat(canceled.subscriptionStatus()).isEqualTo(Status.CANCELED); + assertThat(canceled.allowPublicJoin()).isFalse(); + assertThat(canceled.gameplayAvailable()).isFalse(); + assertThat(canceled.allowNewGameplayBindings()).isFalse(); + assertThat(canceled.allowNewInstanceStarts()).isFalse(); + assertThat(canceled.cutoffAt()).isEqualTo(cancellation); + assertThat(canceled.tenantBillingSequence()).isEqualTo(3); + assertThat( + new String( + one( + c, + "SELECT payload FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = 3", + f.creation().tenantId()) + .get("payload", byte[].class), + java.nio.charset.StandardCharsets.UTF_8)) + .contains("TenantBillingStateChanged"); + f.clock().advance(Duration.ofSeconds(30)); + var laterCanceled = f.service().readCurrent(f.creation().tenantId()); + assertThat(laterCanceled.subscriptionStatus()).isEqualTo(Status.CANCELED); + assertThat(laterCanceled.cutoffAt()).isEqualTo(cancellation); + assertThat(laterCanceled.gameplayAvailable()).isFalse(); + assertThat(laterCanceled.validUntil()).isEqualTo(f.clock().instant().plusSeconds(15)); + assertThat(laterCanceled.tenantBillingSequence()).isEqualTo(3); + assertThat(count(c, "subscription_lifecycle_receipts")).isEqualTo(3); + assertThat( + one( + c, + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + f.creation().requestId()) + .get("released_at")) + .isNull(); + // Effective hosting cutoff is not proof that the provider can no longer charge. Neither the + // typed replacement owner nor structural SQL may strand that still-held original operation. + assertThatThrownBy( + () -> + in( + c, + () -> + c.intents() + .retainPending( + new AccountSubscriptionCreateRequest( + UUID.randomUUID(), + f.creation().tenantId(), + f.creation().owner(), + f.creation().planCode(), + f.instrument().instrumentUuid(), + 1, + new ProducerEvidence( + f.creation().owner().accountUuid(), + UUID.randomUUID(), + DIGEST), + new AccountSubscriptionCreateRequest.ReplacementFence( + f.creation().subscriptionId(), + canceled.current().rowVersion()))))) + .isInstanceOf(AccountSubscriptionIntentRepository.ConflictException.class); + assertSqlState( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription SET superseded_at = clock_timestamp(), " + + "superseded_by_request_id = ?, row_version = row_version + 1 WHERE subscription_id = ?", + UUID.randomUUID(), + f.creation().subscriptionId())); + assertThat(count(c, "subscription_create_operations")).isOne(); + f.transport().json = + response(f, "canceled") + .replace("\"ended_at\":null", "\"ended_at\":" + cancellation.getEpochSecond()); + refresh(f); + assertThat(f.service().readCurrent(f.creation().tenantId()).tenantBillingSequence()) + .isEqualTo(4); + assertThat( + one( + c, + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + f.creation().requestId()) + .get("released_at")) + .isNotNull(); + assertThat(c.intents().lookupProviderId(f.providerId()).disposition()) + .isEqualTo(AccountSubscriptionIntentRepository.MappingDisposition.TERMINAL_HISTORY); + assertThat( + one( + c, + "SELECT row_version FROM payment_instrument WHERE instrument_uuid = ?", + f.instrument().instrumentUuid()) + .get("row_version", Long.class)) + .isOne(); + var beforeReplacement = c.intents().findCurrentByTenant(f.creation().tenantId()).orElseThrow(); + in( + c, + () -> + c.intents() + .retainPending( + new AccountSubscriptionCreateRequest( + UUID.randomUUID(), + f.creation().tenantId(), + f.creation().owner(), + f.creation().planCode(), + f.instrument().instrumentUuid(), + 1, + new ProducerEvidence( + f.creation().owner().accountUuid(), UUID.randomUUID(), DIGEST), + new AccountSubscriptionCreateRequest.ReplacementFence( + f.creation().subscriptionId(), beforeReplacement.rowVersion())))); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + assertThat(count(c, "subscription_lifecycle_receipts")).isEqualTo(4); + assertThat(count(c, "subscription_provider_history")).isOne(); + } + + @Test + void populatedV1029UpgradePreservesIntentQuoteRowAndFlywayHistoryWithoutSynthesizingReceipts() { + Context c = context("1029"); + Fixture f = fixture(c); + var before = + one( + c, + "SELECT row_to_json(s)::text AS value, xmin::text AS xmin FROM subscription s WHERE subscription_id = ?", + f.creation().subscriptionId()); + var intent = + one( + c, + "SELECT row_to_json(o)::text AS value, xmin::text AS xmin FROM subscription_create_operations o WHERE request_id = ?", + f.creation().requestId()); + var history = + c.setup().fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); + configuration(c).target("1030").load().migrate(); + var after = + one( + c, + "SELECT (to_jsonb(s) - 'lifecycle_inflight_request_id' - 'current_receipt_request_id')::text AS value, xmin::text AS xmin " + + "FROM subscription s WHERE subscription_id = ?", + f.creation().subscriptionId()); + // jsonb comparison avoids treating key order as row mutation. + assertThat( + one( + c, + "SELECT ?::jsonb = ?::jsonb AS same", + before.get("value", String.class), + after.get("value", String.class)) + .get("same", Boolean.class)) + .isTrue(); + assertThat(after.get("xmin", String.class)).isEqualTo(before.get("xmin", String.class)); + assertThat( + one( + c, + "SELECT row_to_json(o)::text AS value, xmin::text AS xmin FROM subscription_create_operations o WHERE request_id = ?", + f.creation().requestId())) + .isEqualTo(intent); + var afterHistory = + c.setup().fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); + assertThat(afterHistory).hasSize(history.size() + 1); + assertThat(afterHistory.subList(0, history.size())).isEqualTo(history); + assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); + assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + } + + private static AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim claim(Fixture f) { + return Objects.requireNonNull( + f.service().claimProvisioning(f.creation().requestId(), 1, UUID.randomUUID()).claim()); + } + + @Test + void committedTerminalCancellationReplaysAfterCanceledSubscriptionIsReplaced() { + FailedResolution f = failedResolution(); + Context c = f.fixture.context(); + var owner = f.fixture.owner(); + var prepared = in(c, () -> owner.prepareTerminalResolution(f.request)); + f.fixture.transport().json = response(f.fixture, "canceled"); + var sdk = f.fixture.observer().observe(prepared.binding()); + var committed = + in(c, () -> owner.applyTerminalResolution(prepared, sdk, target -> authorized(f))); + var predecessor = c.intents().findCurrentByTenant(f.request.tenantId()).orElseThrow(); + var successor = + in( + c, + () -> + c.intents() + .retainPending( + new AccountSubscriptionCreateRequest( + UUID.randomUUID(), + f.request.tenantId(), + f.fixture.creation().owner(), + f.fixture.creation().planCode(), + f.fixture.instrument().instrumentUuid(), + 1, + new ProducerEvidence( + f.request.actorAccountId(), UUID.randomUUID(), DIGEST), + new AccountSubscriptionCreateRequest.ReplacementFence( + f.request.subscriptionId(), predecessor.rowVersion())))); + List retained = resolutionImage(c); + var replay = in(c, () -> owner.prepareTerminalResolution(f.request)); + assertThat(replay.replayResult()).isEqualTo(committed); + assertThat( + in( + c, + () -> + owner.applyTerminalResolution( + replay, + null, + target -> { + assertThat(target.currentSubscriptionVersion()) + .isEqualTo(committed.committedRowVersion()); + return authorized(f); + }))) + .isEqualTo(committed); + assertThat(resolutionImage(c)).isEqualTo(retained); + assertThat(c.intents().findCurrentByTenant(f.request.tenantId()).orElseThrow().subscriptionId()) + .isEqualTo(successor.subscriptionId()); + assertThatThrownBy( + () -> + in( + c, + () -> owner.prepareTerminalResolution(withReason(f.request, "changed reason")))) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThat(failedImage(c, f.request.failedRequestId())).isEqualTo(f.failureImage); + } + + @Test + void + terminalCancellationResolutionCommitsOneCanonicalReceiptAndReplaysWithoutChangingFailureHistory() { + FailedResolution f = failedResolution(); + Context c = f.fixture.context(); + var owner = f.fixture.owner(); + List before = resolutionImage(c); + var prepared = in(c, () -> owner.prepareTerminalResolution(f.request)); + assertThat(resolutionImage(c)).isEqualTo(before); + f.fixture.transport().json = response(f.fixture, "canceled"); + var sdk = f.fixture.observer().observe(prepared.binding()); + AtomicInteger callbacks = new AtomicInteger(); + var result = + in( + c, + () -> + owner.applyTerminalResolution( + prepared, + sdk, + target -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat(target.billingOwnerAccountId()) + .isEqualTo( + c.intents() + .findCreation(f.request.creationRequestId()) + .orElseThrow() + .owner() + .accountUuid()); + assertThat(target.currentSubscriptionVersion()) + .isEqualTo(f.request.expectedSubscriptionVersion()); + callbacks.incrementAndGet(); + return authorized(f); + })); + assertThat(result.outcome()).isEqualTo(Outcome.COMMITTED); + assertThat(result.committedRowVersion()).isEqualTo(f.request.expectedSubscriptionVersion() + 2); + assertThat(count(c, "subscription_lifecycle_terminal_resolutions")).isOne(); + assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isOne(); + assertThat(count(c, "account_audit_outbox")).isEqualTo(f.auditRowsBefore + 1); + assertThat(failedImage(c, f.request.failedRequestId())).isEqualTo(f.failureImage); + assertThat(f.fixture.service().readCurrent(f.request.tenantId()).subscriptionStatus()) + .isEqualTo(Status.CANCELED); + List committed = resolutionImage(c); + var replay = in(c, () -> owner.prepareTerminalResolution(f.request)); + assertThat(replay.replayResult()).isEqualTo(result); + assertThat( + in( + c, + () -> + owner.applyTerminalResolution( + replay, + null, + target -> { + callbacks.incrementAndGet(); + return authorized(f); + }))) + .isEqualTo(result); + assertThat(callbacks).hasValue(2); + assertThat(resolutionImage(c)).isEqualTo(committed); + assertThatThrownBy( + () -> + in( + c, + () -> owner.prepareTerminalResolution(withReason(f.request, "changed reason")))) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertSqlState( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription_lifecycle_operations SET state = 'COMMITTED', row_version = row_version + 1 WHERE request_id = ?", + f.request.failedRequestId())); + assertSqlState( + "23514", + () -> + c.setup() + .execute( + "DELETE FROM subscription_lifecycle_operator_outbox WHERE request_id = ?", + f.request.failedRequestId())); + assertSqlState( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription_lifecycle_terminal_resolutions SET audit_reason = 'changed' WHERE resolution_request_id = ?", + f.request.resolutionRequestId())); + assertThat(resolutionImage(c)).isEqualTo(committed); + } + + @Test + void activeUnresolvedStaleAndWrongBindingResolutionEvidenceNeverInvokesAuthorizationOrWrites() { + for (String failure : List.of("active", "unresolved", "stale", "wrong-binding")) { + FailedResolution f = failedResolution(); + Context c = f.fixture.context(); + var prepared = in(c, () -> f.fixture.owner().prepareTerminalResolution(f.request)); + List before = resolutionImage(c); + f.fixture.transport().json = + response(f.fixture, failure.equals("active") ? "active" : "canceled"); + if (failure.equals("unresolved")) f.fixture.transport().failure = mock(StripeException.class); + if (failure.equals("wrong-binding")) + f.fixture.transport().json = + f.fixture.transport().json.replace("price_controlled", "price_other"); + var sdk = f.fixture.observer().observe(prepared.binding()); + if (failure.equals("stale")) f.fixture.clock().advance(Duration.ofSeconds(11)); + AtomicInteger callbacks = new AtomicInteger(); + assertThatThrownBy( + () -> + in( + c, + () -> + f.fixture + .owner() + .applyTerminalResolution( + prepared, + sdk, + target -> { + callbacks.incrementAndGet(); + return authorized(f); + }))) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); + assertThat(callbacks).hasValue(0); + assertThat(resolutionImage(c)).isEqualTo(before); + } + } + + @Test + void deniedAuthorizationAndActualDownstreamSqlFailureRetainFailedFenceAndAllOwnerRows() { + FailedResolution f = failedResolution(); + Context c = f.fixture.context(); + var prepared = in(c, () -> f.fixture.owner().prepareTerminalResolution(f.request)); + f.fixture.transport().json = response(f.fixture, "canceled"); + var sdk = f.fixture.observer().observe(prepared.binding()); + List before = resolutionImage(c); + assertThatThrownBy( + () -> + in( + c, + () -> + f.fixture + .owner() + .applyTerminalResolution( + prepared, + sdk, + target -> { + assertThat( + count(c, "subscription_lifecycle_terminal_resolutions")) + .isZero(); + throw new IllegalStateException( + "controlled primary authentication denial"); + }))) + .hasMessage("controlled primary authentication denial"); + assertThat(resolutionImage(c)).isEqualTo(before); + c.setup() + .execute( + "CREATE FUNCTION reject_resolution_billing() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'controlled resolution billing failure' USING ERRCODE = '23514'; END; $$"); + c.setup() + .execute( + "CREATE TRIGGER reject_resolution_billing BEFORE INSERT ON account_tenant_entitlement_outbox_events FOR EACH ROW EXECUTE FUNCTION reject_resolution_billing()"); + assertSqlState( + "23514", + () -> + in( + c, + () -> + f.fixture + .owner() + .applyTerminalResolution(prepared, sdk, target -> authorized(f)))); + assertThat(resolutionImage(c)).isEqualTo(before); + assertThat(failedImage(c, f.request.failedRequestId())).isEqualTo(f.failureImage); + assertSqlState( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription SET lifecycle_inflight_request_id = NULL, row_version = row_version + 1 WHERE subscription_id = ?", + f.request.subscriptionId())); + assertSqlState( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription SET lifecycle_inflight_request_id = ?, row_version = row_version + 1 WHERE subscription_id = ?", + UUID.randomUUID(), + f.request.subscriptionId())); + assertThat(resolutionImage(c)).isEqualTo(before); + } + + @Test + void resolutionRequiresExactCapturedVersionsSameOwnerAndMatchingFreshAuthorizationSource() { + FailedResolution f = failedResolution(); + Context c = f.fixture.context(); + List before = resolutionImage(c); + for (String changed : List.of("owner", "failed-version", "subscription-version")) { + Request wrong = + new Request( + f.request.resolutionRequestId(), + f.request.failedRequestId(), + f.request.creationRequestId(), + f.request.subscriptionId(), + f.request.tenantId(), + f.request.expectedFailedOperationVersion() + + (changed.equals("failed-version") ? 1 : 0), + f.request.expectedSubscriptionVersion() + + (changed.equals("subscription-version") ? 1 : 0), + changed.equals("owner") ? UUID.randomUUID() : f.request.actorAccountId(), + f.request.controlUiIssuanceOperationId(), + f.request.controlUiTokenHash(), + f.request.auditEventId(), + f.request.auditReason()); + assertThatThrownBy(() -> in(c, () -> f.fixture.owner().prepareTerminalResolution(wrong))) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); + } + var prepared = in(c, () -> f.fixture.owner().prepareTerminalResolution(f.request)); + f.fixture.transport().json = response(f.fixture, "canceled"); + var sdk = f.fixture.observer().observe(prepared.binding()); + assertThatThrownBy( + () -> in(c, () -> f.fixture.owner().applyTerminalResolution(prepared, sdk, null))) + .isInstanceOf(NullPointerException.class); + for (String changed : List.of("actor", "issuance", "hash", "stale-auth")) { + assertThatThrownBy( + () -> + in( + c, + () -> + f.fixture + .owner() + .applyTerminalResolution( + prepared, + sdk, + target -> + new AuthorizedActor( + changed.equals("actor") + ? UUID.randomUUID() + : f.request.actorAccountId(), + changed.equals("issuance") + ? UUID.randomUUID() + : f.request.controlUiIssuanceOperationId(), + changed.equals("hash") + ? "b".repeat(64) + : f.request.controlUiTokenHash(), + changed.equals("stale-auth") + ? f.fixture.clock().instant().minusSeconds(1) + : f.fixture.clock().instant())))) + .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); + } + assertThat(resolutionImage(c)).isEqualTo(before); + } + + @Test + void competingResolutionRequestsCommitExactlyOneAndRejectStaleCapturedTarget() throws Exception { + FailedResolution f = failedResolution(); + Context c = f.fixture.context(); + Request other = + new Request( + UUID.randomUUID(), + f.request.failedRequestId(), + f.request.creationRequestId(), + f.request.subscriptionId(), + f.request.tenantId(), + f.request.expectedFailedOperationVersion(), + f.request.expectedSubscriptionVersion(), + f.request.actorAccountId(), + f.request.controlUiIssuanceOperationId(), + f.request.controlUiTokenHash(), + UUID.randomUUID(), + "second controlled resolution"); + var first = in(c, () -> f.fixture.owner().prepareTerminalResolution(f.request)); + var second = in(c, () -> f.fixture.owner().prepareTerminalResolution(other)); + f.fixture.transport().json = response(f.fixture, "canceled"); + var firstSdk = f.fixture.observer().observe(first.binding()); + var secondSdk = f.fixture.observer().observe(second.binding()); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch go = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + var a = + executor.submit( + () -> { + ready.countDown(); + await(go); + return attemptResolution(f, first, firstSdk); + }); + var b = + executor.submit( + () -> { + ready.countDown(); + await(go); + return attemptResolution(f, second, secondSdk); + }); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + go.countDown(); + assertThat(List.of(a.get(20, TimeUnit.SECONDS), b.get(20, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(true, false); + } finally { + go.countDown(); + executor.shutdownNow(); + } + assertThat(count(c, "subscription_lifecycle_terminal_resolutions")).isOne(); + assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); + assertThat(failedImage(c, f.request.failedRequestId())).isEqualTo(f.failureImage); + } + + private static boolean attemptResolution( + FailedResolution f, + AccountHostingSubscriptionLifecycleRepository.ResolutionPreparation prepared, + StripeHostingSubscriptionObserver.Result sdk) { + try { + in( + f.fixture.context(), + () -> + f.fixture + .owner() + .applyTerminalResolution( + prepared, + sdk, + target -> + new AuthorizedActor( + prepared.request().actorAccountId(), + prepared.request().controlUiIssuanceOperationId(), + prepared.request().controlUiTokenHash(), + f.fixture.clock().instant()))); + return true; + } catch (AccountSubscriptionIntentRepository.FenceRejectedException lostRace) { + return false; + } + } + + private static FailedResolution failedResolution() { + Context c = context("1036"); + Fixture f = fixture(c); + var claim = claim(f); + UUID failed = UUID.randomUUID(); + f.transport().json = response(f, "active").replace("price_controlled", "price_wrong"); + for (int attempt = 1; attempt <= 3; attempt++) { + assertThat( + f.service() + .reconcile(failed, f.creation().requestId(), 2, f.providerId(), claim.attemptId()) + .outcome()) + .isEqualTo(attempt == 3 ? Outcome.TERMINAL_FAILURE : Outcome.RECONCILING); + f.clock().advance(Duration.ofSeconds(2)); + } + long version = + one( + c, + "SELECT row_version FROM subscription_lifecycle_operations WHERE request_id = ?", + failed) + .get(0, Long.class); + long current = + c.intents().findCurrentByTenant(f.creation().tenantId()).orElseThrow().rowVersion(); + Request request = + new Request( + UUID.randomUUID(), + failed, + f.creation().requestId(), + f.creation().subscriptionId(), + f.creation().tenantId(), + version, + current, + f.creation().owner().accountUuid(), + UUID.randomUUID(), + "a".repeat(64), + UUID.randomUUID(), + "Controlled canceled provider recovery"); + return new FailedResolution( + f, request, failedImage(c, failed), count(c, "account_audit_outbox")); + } + + private static AuthorizedActor authorized(FailedResolution f) { + return new AuthorizedActor( + f.request.actorAccountId(), + f.request.controlUiIssuanceOperationId(), + f.request.controlUiTokenHash(), + f.fixture.clock().instant()); + } + + private static Request withReason(Request original, String reason) { + return new Request( + original.resolutionRequestId(), + original.failedRequestId(), + original.creationRequestId(), + original.subscriptionId(), + original.tenantId(), + original.expectedFailedOperationVersion(), + original.expectedSubscriptionVersion(), + original.actorAccountId(), + original.controlUiIssuanceOperationId(), + original.controlUiTokenHash(), + original.auditEventId(), + reason); + } + + private static String failedImage(Context c, UUID failed) { + return one( + c, + "SELECT to_jsonb(operation)::text || to_jsonb(notice)::text FROM subscription_lifecycle_operations operation JOIN subscription_lifecycle_operator_outbox notice USING (request_id) WHERE request_id = ?", + failed) + .get(0, String.class); + } + + private static List resolutionImage(Context c) { + List image = new ArrayList<>(); + for (String table : + List.of( + "subscription", + "subscription_current_observations", + "subscription_lifecycle_operations", + "subscription_lifecycle_attempts", + "subscription_lifecycle_observations", + "subscription_lifecycle_receipts", + "subscription_lifecycle_terminal_resolutions", + "subscription_lifecycle_operator_outbox", + "subscription_provider_history", + "subscription_provider_terminal_resolutions", + "subscription_instrument_reservations", + "account_audit_outbox", + "account_tenant_entitlement_outbox_events", + "account_tenant_authority_source_records", + "account_authority_generations")) { + image.add( + one( + c, + "SELECT coalesce(jsonb_agg(to_jsonb(value) ORDER BY to_jsonb(value)::text)::text, '[]') FROM " + + table + + " value") + .get(0, String.class)); + } + return List.copyOf(image); + } + + /** Controlled authorization callback only; no genuine actor/primary-authentication claim. */ + private record FailedResolution( + Fixture fixture, Request request, String failureImage, long auditRowsBefore) {} + + private static void activate(Fixture f) { + var claim = claim(f); + assertThat( + f.service() + .reconcile( + UUID.randomUUID(), + f.creation().requestId(), + claim.subscriptionRowVersion(), + f.providerId(), + claim.attemptId()) + .outcome()) + .isEqualTo(Outcome.COMMITTED); + } + + private static void refresh(Fixture f) { + long version = + f.context() + .intents() + .findCurrentByTenant(f.creation().tenantId()) + .orElseThrow() + .rowVersion(); + assertThat( + f.service() + .reconcile( + UUID.randomUUID(), f.creation().requestId(), version, f.providerId(), null) + .outcome()) + .isEqualTo(Outcome.COMMITTED); + } + + private static Fixture fixture(Context c) { + long row = ROWS.incrementAndGet(); + UUID account = + one( + c, + "INSERT INTO accounts(username,email,password_hash) VALUES (?, ?, 'controlled-hash') RETURNING account_uuid", + "hosting-" + row, + "hosting-" + row + "@example.test") + .get("account_uuid", UUID.class); + UUID tenant = UUID.randomUUID(); + UUID createRequest = UUID.randomUUID(); + UUID createOperation = UUID.randomUUID(); + String key = "game-" + row; + String requestDigest = + GameTenantCreationDigest.requestDigest( + "prod", createRequest, key, "Controlled hosting", "Storage only"); + var source = + new FreshTenantCreationEvidence( + 1, + "prod", + createRequest, + createOperation, + requestDigest, + tenant, + row, + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", + createRequest, + createOperation, + requestDigest, + tenant, + row, + key, + "NEW_GAME_ROW")); + in( + c, + () -> { + new FreshTenantIdentityAssociationRepository(c.dsl(), "prod").importVerified(source); + return new AccountAuthorityGenerationRepository(c.dsl()).initializeTenantIfAbsent(tenant); + }); + UUID authorization = UUID.randomUUID(); + var creator = + new FreshTenantCreatorEvidence( + 1, + source, + account, + authorization, + DIGEST, + FreshTenantCreatorDigest.evidenceDigest(1, source, account, authorization, DIGEST)); + var owner = + in( + c, + () -> + new AccountInitialTenantBillingOwnerRepository(c.dsl()) + .establishInitial( + new AccountInitialTenantBillingOwnerRepository.InitialRequest( + UUID.randomUUID(), creator, UUID.randomUUID(), 1, true))); + var customers = new AccountBillingCustomerRepository(c.dsl()); + var pendingCustomer = + in(c, () -> customers.retainIntent(account, UUID.randomUUID(), UUID.randomUUID())) + .customer(); + var customer = + in( + c, + () -> + customers.recordObservation( + account, + pendingCustomer.customerProvisioningRequestId(), + 1, + UUID.randomUUID(), + AccountBillingCustomerRecord.Observation.CONFIRMED, + "cus_" + row, + DIGEST)); + var instrument = + in( + c, + () -> + new AccountPaymentInstrumentRepository(c.dsl()) + .retainAttachment( + new AccountPaymentInstrumentRepository.Attachment( + UUID.randomUUID(), + UUID.randomUUID(), + account, + customer.customerProvisioningRequestId(), + customer.providerCustomerId(), + "pm_" + row, + AccountPaymentInstrumentRecord.State.ATTACHABLE, + new AccountPaymentInstrumentRecord.DisplayMetadata( + "visa", "4242", 12, 2030), + DIGEST))); + var creation = + in( + c, + () -> + c.intents() + .retainPending( + new AccountSubscriptionCreateRequest( + UUID.randomUUID(), + tenant, + new OwnerFence(account, owner.ownerVersion(), owner.ownerGeneration()), + "hosting", + instrument.instrumentUuid(), + 1, + new ProducerEvidence(account, UUID.randomUUID(), DIGEST), + null))); + var clock = new MutableClock(creation.createdAt().plusSeconds(1)); + var transport = new ControlledTransport(); + var repository = owner(c, clock, c.intents()); + var observer = + new StripeHostingSubscriptionObserver( + new com.stripe.StripeClient(transport), + clock, + Duration.ofMillis(250), + Duration.ofSeconds(1)); + var service = + new AccountHostingSubscriptionLifecycleService( + repository, observer, new DataSourceTransactionManager(c.source())); + Fixture fixture = + new Fixture( + c, creation, instrument, "sub_" + row, clock, transport, repository, observer, service); + transport.json = response(fixture, "active"); + return fixture; + } + + private static AccountHostingSubscriptionLifecycleRepository owner( + Context c, Clock clock, AccountSubscriptionIntentRepository intents) { + return new AccountHostingSubscriptionLifecycleRepository( + c.dsl(), + intents, + clock, + new ReconciliationLimits( + 4, 3, Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofHours(1)), + new AccountHostingSubscriptionLifecyclePolicy( + Duration.ofSeconds(15), + new RecoveryTiming(Duration.ofSeconds(60), Duration.ofSeconds(120))), + "prod", + false); + } + + private static AccountHostingSubscriptionLifecycleService service( + Context c, + AccountHostingSubscriptionLifecycleRepository owner, + ControlledTransport transport, + Clock clock) { + return new AccountHostingSubscriptionLifecycleService( + owner, + new StripeHostingSubscriptionObserver( + new com.stripe.StripeClient(transport), + clock, + Duration.ofMillis(250), + Duration.ofSeconds(1)), + new DataSourceTransactionManager(c.source())); + } + + @SuppressFBWarnings( + value = "VA_FORMAT_STRING_USES_NEWLINE", + justification = + "This is a JSON test fixture whose text block intentionally retains LF characters independent of the host console line separator.") + private static String response(Fixture f, String status) { + return """ + {"id":"%s","object":"subscription","customer":"%s","default_payment_method":"%s", + "livemode":false,"status":"%s","cancel_at_period_end":false,"cancel_at":null,"canceled_at":null,"ended_at":null, + "metadata":{"firemud_metadata_schema_version":"1","firemud_operation_type":"subscription_provisioning", + "firemud_operation_id":"%s","firemud_subscription_id":"%s"}, + "items":{"object":"list","data":[{"id":"si_controlled","object":"subscription_item","subscription":"%s", + "quantity":1,"current_period_start":%d,"current_period_end":%d,"price":{"id":"%s","object":"price"}}],"has_more":false}} + """ + .formatted( + f.providerId(), + f.creation().providerCustomerId(), + f.instrument().providerPaymentMethodId(), + status, + f.creation().subscriptionProvisioningRequestId(), + f.creation().subscriptionId(), + f.providerId(), + f.creation().createdAt().getEpochSecond(), + f.creation().createdAt().getEpochSecond() + 3600, + f.creation().planQuote().providerPriceId()); + } + + private static Context context(String target) { + String schema = "hosting_lifecycle_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + source.setSchema(schema); + var setup = DSL.using(source, SQLDialect.POSTGRES); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var tx = new TransactionTemplate(new DataSourceTransactionManager(source)); + var catalog = + new AccountHostingPlanCatalog( + List.of( + new AccountHostingPlanCatalog.ConfiguredPlan( + "hosting", "price_controlled", "1", "100", "2", "1048576"))); + var c = + new Context( + source, schema, setup, dsl, tx, new AccountSubscriptionIntentRepository(dsl, catalog)); + configuration(c).target(target).load().migrate(); + return c; + } + + private static FluentConfiguration configuration(Context c) { + return Flyway.configure() + .dataSource(c.source()) + .schemas(c.schema()) + .defaultSchema(c.schema()) + .placeholders(Map.of("serviceSchema", c.schema())) + .locations("classpath:db/migration", "classpath:db/migration/saga"); + } + + private static T in(Context c, Supplier body) { + return Objects.requireNonNull(c.tx().execute(s -> body.get())); + } + + private static org.jooq.Record one(Context c, String sql, Object... bindings) { + return Objects.requireNonNull(c.setup().fetchOne(sql, bindings)); + } + + private static long count(Context c, String table) { + return one(c, "SELECT count(*) FROM " + table).get(0, Long.class); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Controlled SDK read barrier timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Controlled SDK read interrupted", interrupted); + } + } + + private static void assertSqlState(String state, Runnable body) { + assertThatThrownBy(body::run) + .satisfies( + failure -> { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql) { + assertThat(sql.getSQLState()).isEqualTo(state); + return; + } + } + throw new AssertionError("Expected actual PostgreSQL constraint refusal", failure); + }); + } + + private record Context( + DriverManagerDataSource source, + String schema, + DSLContext setup, + DSLContext dsl, + TransactionTemplate tx, + AccountSubscriptionIntentRepository intents) {} + + private record Fixture( + Context context, + AccountSubscriptionCreationRecord creation, + AccountPaymentInstrumentRecord instrument, + String providerId, + MutableClock clock, + ControlledTransport transport, + AccountHostingSubscriptionLifecycleRepository owner, + StripeHostingSubscriptionObserver observer, + AccountHostingSubscriptionLifecycleService service) {} + + private static final class MutableClock extends Clock { + private Instant current; + + MutableClock(Instant current) { + this.current = current; + } + + void advance(Duration amount) { + current = current.plus(amount); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return current; + } + } + + private static final class ControlledTransport implements StripeResponseGetter { + private String json; + private StripeException failure; + private Runnable duringRead; + private int reads; + + @Override + @SuppressWarnings("unchecked") + public T request( + BaseAddress address, + RequestMethod method, + String path, + Map params, + Type type, + RequestOptions options, + ApiMode mode) + throws StripeException { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(method).isEqualTo(RequestMethod.GET); + assertThat(path).startsWith("/v1/subscriptions/"); + reads++; + Runnable action = duringRead; + duringRead = null; + if (action != null) { + action.run(); + } + if (failure != null) { + throw failure; + } + return (T) com.stripe.net.ApiResource.GSON.fromJson(json, type); + } + + @Override + public InputStream requestStream( + BaseAddress address, + RequestMethod method, + String path, + Map params, + RequestOptions options, + ApiMode mode) + throws StripeException { + throw new AssertionError("No streaming or provider mutations are allowed"); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java new file mode 100644 index 0000000000..22f2b6903d --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java @@ -0,0 +1,1879 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.SQLException; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRecord.DisplayMetadata; +import net.firedevops.firemud.accountservice.repository.AccountPaymentInstrumentRepository.Attachment; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.ProducerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.ReplacementFence; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.ConflictException; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.MappingDisposition; +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.test.TestContainerImages; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual PostgreSQL persistence/concurrency sources using CONTROLLED owner/provider evidence. These + * fixtures do not qualify genuine authenticated producers, Stripe, lifecycle/outbox dispatch, + * transfers, downstream readers or production admission. No trigger is disabled to construct them. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountSubscriptionIntentPostgresIntegrationTest { + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final OffsetDateTime BOUNDARY = OffsetDateTime.parse("2026-11-01T00:00:00Z"); + private static final AtomicLong GAME_ROWS = new AtomicLong(100); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void durableProvisioningClaimReplaysAfterRecreationAndRecoversOnlyTheOriginalBinding() { + Context c = context(); + configuration(c).target("1030").load().migrate(); + Seed seed = seed(c); + var created = create(c, request(seed, UUID.randomUUID(), 1, null)); + UUID attemptId = UUID.randomUUID(); + var first = + Objects.requireNonNull( + c.tx().execute(s -> lifecycle(c).claim(created.requestId(), 1, attemptId))) + .claim(); + assertThat(first.creation()).isEqualTo(created); + assertThat(first.subscriptionRowVersion()).isEqualTo(2); + assertThat(first.attemptNumber()).isEqualTo(1); + assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().status()) + .isEqualTo("provisioning"); + assertThat( + c.repository() + .findCurrentByTenant(seed.tenant()) + .orElseThrow() + .providerSubscriptionId()) + .isNull(); + var replay = + Objects.requireNonNull( + c.tx().execute(s -> lifecycle(c).claim(created.requestId(), 1, attemptId))) + .claim(); + assertThat(replay.attemptId()).isEqualTo(first.attemptId()); + assertThat(replay.subscriptionRowVersion()).isEqualTo(first.subscriptionRowVersion()); + assertThat(replay.expiresAt()).isEqualTo(first.expiresAt()); + assertThat(count(c, "subscription_provisioning_attempts")).isOne(); + assertThat(databaseNow(c)).isBefore(first.expiresAt()); + var waiting = + Objects.requireNonNull( + c.tx().execute(s -> lifecycle(c).claim(created.requestId(), 2, UUID.randomUUID()))); + assertThat(waiting.disposition()) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.WAITING); + sleepUntil(c, first.expiresAt().plusMillis(6)); + var recovered = + Objects.requireNonNull( + c.tx().execute(s -> lifecycle(c).claim(created.requestId(), 2, UUID.randomUUID()))) + .claim(); + // Attempt history does not grant provider IO; the independent dispatch receipt owns it. + assertThat(recovered.attemptNumber()).isEqualTo(2); + assertThat(recovered.creation()).isEqualTo(created); + assertThat(recovered.subscriptionRowVersion()).isEqualTo(3); + assertThat(recovered.attemptId()).isNotEqualTo(first.attemptId()); + assertThat(count(c, "subscription_provisioning_attempts")).isEqualTo(2); + assertThatThrownBy(() -> c.tx().execute(s -> lifecycle(c).deferUnresolved(first))) + .isInstanceOf(FenceRejectedException.class); + assertThat( + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + created.requestId()), + "Expected retained reservation") + .get("released_at")) + .isNull(); + assertThat(count(c, "subscription_provider_history")).isZero(); + assertThat(count(c, "account_tenant_entitlement_outbox_events")).isZero(); + } + + @Test + void provisioningExhaustionCommitsOneOperatorItemWithoutCancellationOrWalletRewrite() { + Context c = context(); + configuration(c).target("1030").load().migrate(); + Seed seed = seed(c); + var created = create(c, request(seed, UUID.randomUUID(), 1, null)); + var first = + Objects.requireNonNull( + c.tx().execute(s -> lifecycle(c).claim(created.requestId(), 1, UUID.randomUUID()))) + .claim(); + var firstDeferred = c.tx().execute(s -> lifecycle(c).deferUnresolved(first)); + assertThat(firstDeferred) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.WAITING); + Instant retryAt = + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT retry_at FROM subscription_provisioning_work WHERE request_id = ?", + created.requestId())) + .get("retry_at", OffsetDateTime.class) + .toInstant(); + sleepUntil(c, retryAt.plusMillis(5)); + var second = + Objects.requireNonNull( + c.tx().execute(s -> lifecycle(c).claim(created.requestId(), 2, UUID.randomUUID()))) + .claim(); + var exhausted = c.tx().execute(s -> lifecycle(c).deferUnresolved(second)); + assertThat(exhausted) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); + var exhaustedReplay = c.tx().execute(s -> lifecycle(c).deferUnresolved(second)); + assertThat(exhaustedReplay) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); + assertThat(count(c, "subscription_provisioning_operator_outbox")).isOne(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); + var current = c.repository().findCurrentByTenant(seed.tenant()).orElseThrow(); + assertThat(current.status()).isEqualTo("provisioning"); + assertThat(current.terminalResolutionId()).isNull(); + assertThat(current.rowVersion()).isEqualTo(3); + assertThat( + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT row_version FROM payment_instrument WHERE instrument_uuid = ?", + seed.instrument().instrumentUuid()), + "Expected retained instrument") + .get("row_version", Long.class)) + .isOne(); + assertThat( + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + created.requestId()), + "Expected retained reservation") + .get("released_at")) + .isNull(); + rejectSql( + "23514", + () -> + c.setup() + .execute("UPDATE subscription_provisioning_operator_outbox SET reason = reason")); + rejectSql("23514", () -> c.setup().execute("DELETE FROM subscription_provisioning_attempts")); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.EnumSource( + value = AccountPaymentInstrumentRecord.State.class, + names = {"ATTACHABLE", "UNAVAILABLE"}) + void claimRollbackAndStaleReservedWalletRetainOneTerminalOperatorItem( + AccountPaymentInstrumentRecord.State observedState) { + Context c = context(); + configuration(c).target("1030").load().migrate(); + Seed seed = seed(c); + var created = create(c, request(seed, UUID.randomUUID(), 1, null)); + c.tx() + .executeWithoutResult( + s -> { + lifecycle(c).claim(created.requestId(), 1, UUID.randomUUID()); + s.setRollbackOnly(); + }); + assertThat(count(c, "subscription_provisioning_work")).isZero(); + assertThat(count(c, "subscription_provisioning_attempts")).isZero(); + var pending = c.repository().findCurrentByTenant(seed.tenant()).orElseThrow(); + assertThat(pending.status()).isEqualTo("pending"); + var observed = + c.tx() + .execute( + s -> + new AccountPaymentInstrumentRepository(c.dsl()) + .recordAvailability( + new AccountPaymentInstrumentRepository.AvailabilityObservation( + UUID.randomUUID(), + seed.instrument().instrumentUuid(), + seed.owner().accountUuid(), + 1L, + observedState, + seed.instrument().display(), + DIGEST))); + // Upgrade the original pending intent and its changed wallet without recreating either row. + configuration(c).load().migrate(); + assertThatThrownBy( + () -> + c.tx().execute(s -> lifecycle(c).claim(created.requestId(), 2, UUID.randomUUID()))) + .isInstanceOf(FenceRejectedException.class); + // Provisioning boundaries use PostgreSQL clock_timestamp(); an injected Java clock cannot + // move the database clock before this durable creation time. The wrong-version fence above + // and rollback proof below exercise the supported database-owned claim boundaries. + c.tx() + .executeWithoutResult( + s -> { + assertThat( + lifecycle(c).claim(created.requestId(), 1, UUID.randomUUID()).disposition()) + .isEqualTo( + AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); + s.setRollbackOnly(); + }); + assertThat(count(c, "subscription_provisioning_work")).isZero(); + assertThat(count(c, "subscription_provisioning_operator_outbox")).isZero(); + UUID firstAttempt = UUID.randomUUID(); + for (UUID attempt : List.of(firstAttempt, firstAttempt, UUID.randomUUID())) { + var result = + Objects.requireNonNull( + c.tx().execute(s -> lifecycle(c).claim(created.requestId(), 1, attempt))); + assertThat(result.disposition()) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); + assertThat(result.claim()).isNull(); + } + assertThat( + Objects.requireNonNull( + c.tx() + .execute( + s -> lifecycle(c).claim(created.requestId(), 1, UUID.randomUUID()))) + .disposition()) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); + assertThat(count(c, "subscription_provisioning_work")).isOne(); + assertThat(count(c, "subscription_provisioning_attempts")).isZero(); + assertThat(count(c, "subscription_provider_dispatch_claim")).isZero(); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); + assertThat(count(c, "subscription_provisioning_operator_outbox")).isOne(); + var work = + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT * FROM subscription_provisioning_work WHERE request_id = ?", + created.requestId())); + assertThat(work.get("phase", String.class)) + .isEqualTo("BILLING_RECONCILIATION_TERMINAL_FAILURE"); + assertThat(work.get("attempt_count", Integer.class)).isZero(); + assertThat(work.get("row_version", Long.class)).isEqualTo(2L); + assertThat(work.get("last_attempt_id")).isNull(); + var notice = + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT * FROM subscription_provisioning_operator_outbox WHERE request_id = ?", + created.requestId())); + assertThat(notice.get("reason", String.class)).isEqualTo("RESERVED_INSTRUMENT_CHANGED"); + assertThat(notice.get("recorded_at")).isEqualTo(work.get("terminal_at")); + assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow()).isEqualTo(pending); + assertThat( + new AccountPaymentInstrumentRepository(c.dsl()) + .findByOwner(seed.owner().accountUuid(), seed.instrument().instrumentUuid()) + .orElseThrow()) + .isEqualTo(observed); + assertThat( + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + created.requestId())) + .get("released_at")) + .isNull(); + } + + @Test + void concurrentProvisioningClaimsHaveOneCurrentVersionWinner() throws Exception { + Context c = context(); + configuration(c).target("1030").load().migrate(); + Seed seed = seed(c); + var created = create(c, request(seed, UUID.randomUUID(), 1, null)); + Supplier attempt = + () -> { + try { + return Objects.requireNonNull( + c.tx() + .execute( + s -> lifecycle(c).claim(created.requestId(), 1, UUID.randomUUID()))) + .disposition() + .name(); + } catch (FenceRejectedException stale) { + return "FENCED"; + } + }; + assertThat(race(attempt, attempt)).containsExactlyInAnyOrder("CLAIMED", "FENCED"); + assertThat(count(c, "subscription_provisioning_attempts")).isOne(); + assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().rowVersion()) + .isEqualTo(2); + } + + @Test + void expiredIntentCreatesUnresolvedFailureWithoutClaimingProviderWork() { + Context c = context(); + configuration(c).target("1030").load().migrate(); + Seed seed = seed(c); + var created = create(c, request(seed, UUID.randomUUID(), 1, null)); + Duration provisioningTimeout = Duration.ofSeconds(3); + sleepUntil(c, created.createdAt().plus(provisioningTimeout).plusMillis(5)); + var expired = + Objects.requireNonNull( + c.tx() + .execute( + s -> + lifecycle(c, provisioningTimeout) + .claim(created.requestId(), 1, UUID.randomUUID()))); + assertThat(expired.disposition()) + .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); + assertThat(expired.claim()).isNull(); + assertThat(count(c, "subscription_provisioning_attempts")).isZero(); + assertThat(count(c, "subscription_provisioning_operator_outbox")).isOne(); + assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().status()) + .isEqualTo("pending"); + } + + private static AccountHostingSubscriptionLifecycleRepository lifecycle(Context c) { + return lifecycle(c, Duration.ofHours(1)); + } + + private static AccountHostingSubscriptionLifecycleRepository lifecycle( + Context c, Duration absoluteTimeout) { + return new AccountHostingSubscriptionLifecycleRepository( + c.dsl(), + c.repository(), + Clock.systemUTC(), + new AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits( + 2, 3, Duration.ofSeconds(3), Duration.ofMillis(1), absoluteTimeout), + new AccountHostingSubscriptionLifecyclePolicy( + Duration.ofSeconds(15), + new AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming( + Duration.ofSeconds(60), Duration.ofSeconds(120))), + "prod", + false); + } + + private static Instant databaseNow(Context c) { + return Objects.requireNonNull(c.setup().fetchOne("SELECT clock_timestamp() AS now")) + .get("now", OffsetDateTime.class) + .toInstant(); + } + + private static void sleepUntil(Context c, Instant deadline) { + c.setup().execute("SELECT pg_sleep_until(?::timestamptz)", deadline.atOffset(ZoneOffset.UTC)); + } + + @Test + void + combinedForwardUpgradePreservesOriginalNumericRowsAndPublishedHistoryWithoutInferringWinners() { + Context c = predecessor(); + var rows = + c.setup() + .fetch( + "SELECT row_to_json(s)::text AS value, xmin::text AS xmin, ctid::text AS ctid FROM subscription s ORDER BY id") + .intoMaps(); + var accounts = + c.setup() + .fetch( + "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM accounts a ORDER BY id") + .intoMaps(); + var history = + c.setup().fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); + + configuration(c).target("1029").load().migrate(); + + assertThat( + c.setup() + .fetch( + "SELECT row_to_json(s)::text AS value, xmin::text AS xmin, ctid::text AS ctid FROM account_retained_subscription_evidence s ORDER BY id") + .intoMaps()) + .isEqualTo(rows); + assertThat( + c.setup() + .fetch( + "SELECT row_to_json(a)::text AS value, xmin::text AS xmin FROM accounts a ORDER BY id") + .intoMaps()) + .isEqualTo(accounts); + var afterHistory = + c.setup().fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); + assertThat(afterHistory).hasSize(history.size() + 5); + assertThat(afterHistory.subList(history.size(), afterHistory.size())) + .extracting(row -> row.get("version")) + .containsExactly("1027", "1027.1", "1027.2", "1028", "1029"); + assertThat(afterHistory.subList(0, history.size())).containsExactlyElementsOf(history); + assertThat( + c.setup() + .fetch( + "SELECT version FROM flyway_schema_history WHERE version IN ('1000','1001','1002')")) + .hasSize(3); + assertThat(count(c, "subscription")).isZero(); + assertThat(count(c, "subscription_create_operations")).isZero(); + assertThat(count(c, "subscription_provider_history")).isZero(); + assertThat( + c.setup() + .fetch( + "SELECT tenant_id FROM subscription WHERE superseded_at IS NULL GROUP BY tenant_id HAVING count(*) > 1")) + .isEmpty(); + assertThat( + c.setup() + .fetch( + "SELECT provider_subscription_id FROM subscription WHERE superseded_at IS NULL AND provider_subscription_id IS NOT NULL GROUP BY provider_subscription_id HAVING count(*) <> 1")) + .isEmpty(); + assertThat(indexDefinition(c, "uq_subscription_active_tenant")) + .contains("UNIQUE", "tenant_id", "superseded_at IS NULL"); + assertThat(indexDefinition(c, "uq_subscription_active_provider")) + .contains("UNIQUE", "provider_subscription_id IS NOT NULL", "superseded_at IS NULL"); + rejectSql( + "23514", + () -> + c.setup().execute("UPDATE account_retained_subscription_evidence SET status = status")); + configuration(c).target("1029").load().validate(); + } + + @Test + void + pendingRetainsExactOriginalResultSeparateIdentitiesReservationAndOutboxAndRejectsChangedRequest() { + Context c = context(); + Seed seed = seed(c); + var request = request(seed, UUID.randomUUID(), 1, null); + var created = create(c, request); + assertThat(created.requestDigest()) + .isEqualTo( + AccountSubscriptionCreateDigest.encode( + seed.tenant(), c.account(), "basic-hosting", seed.instrument().instrumentUuid()) + .digest()); + assertThat(created.initialStatus()).isEqualTo("pending"); + assertThat(created.initialRowVersion()).isOne(); + assertThat( + List.of( + created.requestId(), + created.subscriptionProvisioningRequestId(), + created.cleanupProviderIdentity(), + created.customerProvisioningRequestId())) + .doesNotHaveDuplicates(); + var customer = + new AccountBillingCustomerRepository(c.dsl()).findByAccount(c.account()).orElseThrow(); + assertThat(created.subscriptionProvisioningRequestId()) + .isNotEqualTo(customer.providerIdempotencyId()); + assertThat(created.cleanupProviderIdentity()).isNotEqualTo(customer.providerIdempotencyId()); + assertThat( + c.repository() + .findCurrentByTenant(seed.tenant()) + .orElseThrow() + .providerSubscriptionId()) + .isNull(); + assertThat( + Objects.requireNonNull( + c.tx().execute(s -> c.repository().lockPendingForClaim(request.requestId(), 1))) + .status()) + .isEqualTo("pending"); + assertThat(create(c, request)).isEqualTo(created); + assertThat(count(c, "subscription_create_outbox")).isOne(); + assertThat(count(c, "subscription_instrument_reservations")).isOne(); + assertThat(count(c, "subscription_create_provider_identities")).isEqualTo(2); + var changed = + new AccountSubscriptionCreateRequest( + request.requestId(), + seed.tenant(), + seed.owner(), + "pro-hosting", + seed.instrument().instrumentUuid(), + 1, + producer(c.account()), + null); + assertThatThrownBy(() -> create(c, changed)) + .isInstanceOf(ConflictException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThat(count(c, "subscription")).isOne(); + controlledTerminalCleanup(c, created); + assertThat(create(c, request)) + .isEqualTo(created); // Never rebuild the result from canceled current state. + assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().status()) + .isEqualTo("canceled"); + } + + @Test + void + frozenServerQuoteReplaysAfterCatalogChangeOrRemovalWithoutChangingCallerDigestOrReservation() { + Context c = context(); + Seed first = seed(c); + var request = request(first, UUID.randomUUID(), 1, null); + var created = create(c, request); + var quote = configuredPlans().resolve("basic-hosting"); + assertThat(created.planQuote()).isEqualTo(quote); + var retained = + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT * FROM subscription_create_operations WHERE request_id = ?", + created.requestId())); + assertThat(retained.get("plan_quote_payload", byte[].class)).containsExactly(quote.payload()); + assertThat(retained.get("plan_quote_digest", String.class)).isEqualTo(quote.digest()); + assertThat(retained.get("provider_price_id", String.class)).isEqualTo(quote.providerPriceId()); + assertThat(retained.get("provider_quantity", Long.class)).isEqualTo(quote.providerQuantity()); + assertThat(retained.get("max_active_sessions", Long.class)) + .isEqualTo(quote.maxActiveSessions()); + assertThat(retained.get("max_concurrent_game_instances", Long.class)) + .isEqualTo(quote.maxConcurrentGameInstances()); + assertThat(retained.get("max_storage_bytes", Long.class)).isEqualTo(quote.maxStorageBytes()); + var changedCatalog = + new AccountHostingPlanCatalog( + List.of( + new AccountHostingPlanCatalog.ConfiguredPlan( + "basic-hosting", "price_controlledLater", "9", "200", "4", "2097152"))); + var changedRepository = new AccountSubscriptionIntentRepository(c.dsl(), changedCatalog); + assertThat( + c.tx() + .execute( + s -> changedRepository.retainPending(request))) + .isEqualTo(created); + var removedCatalogRepository = + new AccountSubscriptionIntentRepository(c.dsl(), new AccountHostingPlanCatalog(List.of())); + assertThat( + c.tx() + .execute( + s -> removedCatalogRepository.retainPending(request))) + .isEqualTo(created); + assertThat(changedRepository.findCurrentByTenant(first.tenant()).orElseThrow().planQuote()) + .isEqualTo(quote); + assertThat( + Objects.requireNonNull( + c.tx() + .execute( + s -> changedRepository.lockPendingForClaim(request.requestId(), 1))) + .planQuote()) + .isEqualTo(quote); + Seed second = seed(c); + var later = + Objects.requireNonNull( + c.tx() + .execute( + s -> + changedRepository.retainPending( + request(second, UUID.randomUUID(), 1, null)))); + assertThat(later.planQuote()).isEqualTo(changedCatalog.resolve("basic-hosting")); + assertThat(later.planQuote().digest()).isNotEqualTo(created.planQuote().digest()); + assertThat(created.requestDigest()) + .isEqualTo( + AccountSubscriptionCreateDigest.encode( + first.tenant(), + first.owner().accountUuid(), + request.planCode(), + request.paymentInstrumentId()) + .digest()); + var conflict = + new AccountSubscriptionCreateRequest( + request.requestId(), + request.tenantId(), + request.owner(), + "pro-hosting", + request.paymentInstrumentId(), + request.instrumentVersion(), + request.producer(), + null); + assertThatThrownBy(() -> c.tx().execute(s -> changedRepository.retainPending(conflict))) + .isInstanceOf(ConflictException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThat(count(c, "subscription_create_operations")).isEqualTo(2); + assertThat(count(c, "subscription_instrument_reservations")).isEqualTo(2); + assertThat(count(c, "subscription_create_outbox")).isEqualTo(2); + assertThat(count(c, "subscription_provider_history")).isZero(); + assertThat(changedRepository.findCreation(request.requestId())).contains(created); + } + + @Test + void missingServerPlanConfigurationCreatesNoIntentReservationOrWorkItem() { + Context c = context(); + Seed seed = seed(c); + var unconfigured = + new AccountSubscriptionIntentRepository(c.dsl(), new AccountHostingPlanCatalog(List.of())); + assertThatThrownBy( + () -> + c.tx() + .execute( + s -> unconfigured.retainPending(request(seed, UUID.randomUUID(), 1, null)))) + .isInstanceOf(AccountHostingPlanCatalog.PlanUnavailableException.class); + assertThat(count(c, "subscription_create_operations")).isZero(); + assertThat(count(c, "subscription")).isZero(); + assertThat(count(c, "subscription_instrument_reservations")).isZero(); + assertThat(count(c, "subscription_create_outbox")).isZero(); + } + + @Test + void directSqlQuoteBytesDigestAndProjectedFieldsMustAgreeAndRetainedQuoteCannotBeRewritten() { + Context c = context(); + Seed seed = seed(c); + var request = request(seed, UUID.randomUUID(), 1, null); + var quote = configuredPlans().resolve(request.planCode()); + rejectSql( + "23514", + () -> + c.tx() + .executeWithoutResult( + s -> + insertBareOperationWithQuote( + c, + request, + seed, + UUID.randomUUID(), + UUID.randomUUID(), + quote, + quote.payload(), + "sha256:" + "0".repeat(64)))); + for (var changedFields : + List.of( + new AccountHostingPlanQuote( + quote.planCode(), "price_substituted", quote.providerQuantity(), 100, 2, 1048576), + new AccountHostingPlanQuote( + quote.planCode(), quote.providerPriceId(), 2, 100, 2, 1048576), + new AccountHostingPlanQuote( + quote.planCode(), + quote.providerPriceId(), + quote.providerQuantity(), + 101, + 2, + 1048576), + new AccountHostingPlanQuote( + quote.planCode(), + quote.providerPriceId(), + quote.providerQuantity(), + 100, + 3, + 1048576), + new AccountHostingPlanQuote( + quote.planCode(), + quote.providerPriceId(), + quote.providerQuantity(), + 100, + 2, + 1048577))) { + rejectSql( + "23514", + () -> + c.tx() + .executeWithoutResult( + s -> + insertBareOperationWithQuote( + c, + request, + seed, + UUID.randomUUID(), + UUID.randomUUID(), + changedFields, + quote.payload(), + quote.digest()))); + } + byte[] alteredBytes = Arrays.copyOf(quote.payload(), quote.payload().length + 1); + alteredBytes[alteredBytes.length - 1] = ' '; + rejectSql( + "23514", + () -> + c.tx() + .executeWithoutResult( + s -> + insertBareOperationWithQuote( + c, + request, + seed, + UUID.randomUUID(), + UUID.randomUUID(), + quote, + alteredBytes, + quote.digest()))); + assertThat(count(c, "subscription_create_operations")).isZero(); + var created = create(c, request); + rejectSql( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription_create_operations SET provider_quantity = 2 WHERE request_id = ?", + request.requestId())); + rejectSql( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription SET plan_quote_digest = ?, row_version = row_version + 1 WHERE subscription_id = ?", + "sha256:" + "f".repeat(64), + created.subscriptionId())); + assertThat(c.repository().findCreation(request.requestId())).contains(created); + assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().planQuote()) + .isEqualTo(quote); + } + + @Test + void concurrentEmptyTenantCreatesHaveOneWinnerAndConcurrentExactRetriesReplayOneResult() + throws Exception { + Context c = context(); + Seed seed = seed(c); + var request = request(seed, UUID.randomUUID(), 1, null); + List retries = + race(() -> create(c, request), () -> create(c, request)); + assertThat(retries.getLast()).isEqualTo(retries.getFirst()); + assertThat(count(c, "subscription")).isOne(); + Seed empty = seed(c); + var left = request(empty, UUID.randomUUID(), 1, null); + var right = request(empty, UUID.randomUUID(), 1, null); + assertThat(race(() -> attemptCreate(c, left), () -> attemptCreate(c, right))) + .containsExactlyInAnyOrder("APPLIED", "CONFLICT"); + assertThat( + c.setup() + .fetch( + "SELECT * FROM subscription WHERE tenant_id = ? AND superseded_at IS NULL", + empty.tenant())) + .hasSize(1); + assertThat(count(c, "subscription_create_outbox")).isEqualTo(2); + } + + @Test + void unauditedOwnerAdvanceIsRefusedAndStaleOwnerCapturesCannotCreateIntent() { + Context c = context(); + Seed seed = seed(c); + var before = + c.setup() + .fetch( + "SELECT row_to_json(o)::text AS value, xmin::text AS xmin FROM account_tenant_billing_owners o WHERE tenant_uuid = ?", + seed.tenant()) + .intoMaps(); + rejectSql( + "23514", + () -> + c.tx() + .executeWithoutResult( + status -> + c.dsl() + .execute( + "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, owner_generation = ? WHERE tenant_uuid = ?", + UUID.randomUUID(), + seed.tenant()))); + assertThat( + c.setup() + .fetch( + "SELECT row_to_json(o)::text AS value, xmin::text AS xmin FROM account_tenant_billing_owners o WHERE tenant_uuid = ?", + seed.tenant()) + .intoMaps()) + .isEqualTo(before); + // These are stale comparison inputs, not a fabricated committed transfer or authority grant. + for (var stale : + List.of( + new OwnerFence( + seed.owner().accountUuid(), seed.owner().version() + 1, seed.owner().generation()), + new OwnerFence( + seed.owner().accountUuid(), seed.owner().version(), UUID.randomUUID()))) { + var captured = new Seed(seed.tenant(), stale, seed.instrument()); + assertThat(attemptCreate(c, request(captured, UUID.randomUUID(), 1, null))) + .isEqualTo("FENCED"); + } + assertThat(count(c, "subscription_create_operations")).isZero(); + assertThat(count(c, "subscription_create_outbox")).isZero(); + assertThat(count(c, "subscription_instrument_reservations")).isZero(); + } + + @Test + void instrumentAdvanceThatCommitsFirstFencesQueuedCreateWithoutPartialIntent() throws Exception { + Context walletContext = context(); + Seed walletSeed = seed(walletContext); + var walletRequest = request(walletSeed, UUID.randomUUID(), 1, null); + advanceBeforeCreate( + walletContext, + walletRequest, + () -> + new AccountPaymentInstrumentRepository(walletContext.dsl()) + .recordAvailability( + new AccountPaymentInstrumentRepository.AvailabilityObservation( + UUID.randomUUID(), + walletSeed.instrument().instrumentUuid(), + walletContext.account(), + 1, + AccountPaymentInstrumentRecord.State.UNAVAILABLE, + walletSeed.instrument().display(), + DIGEST))); + assertThat(count(walletContext, "subscription_create_operations")).isZero(); + assertThat(count(walletContext, "subscription_create_outbox")).isZero(); + assertThat(count(walletContext, "subscription_instrument_reservations")).isZero(); + } + + @Test + void commitRechecksSameTransactionOwnerAndWalletChangesAndClaimReadRejectsStaleReservation() { + Context c = context(); + Seed seed = seed(c); + var request = request(seed, UUID.randomUUID(), 1, null); + rejectSql( + "23514", + () -> + c.tx() + .executeWithoutResult( + s -> { + c.repository().retainPending(request); + c.dsl() + .execute( + "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, owner_generation = ? WHERE tenant_uuid = ?", + UUID.randomUUID(), + seed.tenant()); + })); + assertThat(count(c, "subscription")).isZero(); + rejectSql( + "23514", + () -> + c.tx() + .executeWithoutResult( + s -> { + c.repository().retainPending(request); + advanceWallet(c, seed.instrument().instrumentUuid(), UUID.randomUUID()); + })); + assertThat(count(c, "subscription_create_operations")).isZero(); + create(c, request); + c.tx() + .executeWithoutResult( + s -> advanceWallet(c, seed.instrument().instrumentUuid(), UUID.randomUUID())); + assertThatThrownBy( + () -> c.tx().execute(s -> c.repository().lockPendingForClaim(request.requestId(), 1))) + .isInstanceOf(FenceRejectedException.class); + assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().status()) + .isEqualTo("pending"); + assertThat( + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT released_at FROM subscription_instrument_reservations WHERE request_id = ?", + request.requestId()), + "Expected retained reservation") + .get(0)) + .isNull(); + } + + @Test + void canceledCurrentReplacementIsAtomicVersionedDistinctAndOneConcurrentReplacementWins() + throws Exception { + Context c = context(); + Seed seed = seed(c); + var originalRequest = request(seed, UUID.randomUUID(), 1, null); + var original = create(c, originalRequest); + controlledTerminalCleanup(c, original); + var canceled = c.repository().findCurrentByTenant(seed.tenant()).orElseThrow(); + var replacement = + request( + seed, + UUID.randomUUID(), + 1, + new ReplacementFence(original.subscriptionId(), canceled.rowVersion())); + c.tx() + .executeWithoutResult( + s -> { + c.repository().retainPending(replacement); + s.setRollbackOnly(); + }); + assertThat(c.repository().findCurrentByTenant(seed.tenant())).contains(canceled); + assertThat(count(c, "subscription")).isOne(); + assertThat(count(c, "subscription_current_observations")).isEqualTo(2); + var stale = + request(seed, UUID.randomUUID(), 1, new ReplacementFence(original.subscriptionId(), 1)); + assertThatThrownBy(() -> create(c, stale)).isInstanceOf(FenceRejectedException.class); + var competing = + request( + seed, + UUID.randomUUID(), + 1, + new ReplacementFence(original.subscriptionId(), canceled.rowVersion())); + assertThat(race(() -> attemptCreate(c, replacement), () -> attemptCreate(c, competing))) + .containsExactlyInAnyOrder("APPLIED", "FENCED"); + var current = c.repository().findCurrentByTenant(seed.tenant()).orElseThrow(); + assertThat(current.subscriptionId()).isNotEqualTo(original.subscriptionId()); + var successor = c.repository().findCreation(current.creationRequestId()).orElseThrow(); + assertThat(successor.subscriptionProvisioningRequestId()) + .isNotEqualTo(original.subscriptionProvisioningRequestId()); + assertThat(successor.cleanupProviderIdentity()) + .isNotIn(original.subscriptionProvisioningRequestId(), original.cleanupProviderIdentity()); + var retained = + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT * FROM subscription WHERE subscription_id = ?", + original.subscriptionId())); + assertThat(retained.get("superseded_at")).isNotNull(); + assertThat(retained.get("superseded_by_request_id", UUID.class)) + .isEqualTo(current.creationRequestId()); + assertThat(retained.get("row_version", Long.class)).isEqualTo(canceled.rowVersion() + 1); + assertThat(create(c, originalRequest)).isEqualTo(original); + rejectSql( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription SET row_version = row_version + 1 WHERE subscription_id = ?", + original.subscriptionId())); + } + + @Test + void directSqlRejectsIdentityMutationDuplicateCurrentProviderAndUnconfirmedActiveState() { + Context c = context(); + Seed first = seed(c); + Seed second = seed(c); + var one = create(c, request(first, UUID.randomUUID(), 1, null)); + var two = create(c, request(second, UUID.randomUUID(), 1, null)); + for (String assignment : + List.of( + "subscription_id = '11111111-1111-4111-8111-111111111111'::uuid", + "tenant_id = '22222222-2222-4222-8222-222222222222'::uuid", + "plan_code = 'other-plan'", + "account_uuid = '33333333-3333-4333-8333-333333333333'::uuid", + "payment_instrument_id = '44444444-4444-4444-8444-444444444444'::uuid")) { + rejectSql( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription SET " + + assignment + + ", row_version = row_version + 1 WHERE subscription_id = ?", + one.subscriptionId())); + } + rejectSql( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription SET status = 'active', row_version = row_version + 1 WHERE subscription_id = ?", + one.subscriptionId())); + rejectSql( + "23505", + () -> + c.tx() + .executeWithoutResult( + s -> + c.dsl() + .execute( + "UPDATE subscription SET provider_subscription_id = 'sub_duplicate', row_version = row_version + 1 WHERE subscription_id IN (?, ?)", + one.subscriptionId(), + two.subscriptionId()))); + rejectSql( + "23503", + () -> + c.tx() + .executeWithoutResult( + s -> + c.dsl() + .execute( + "UPDATE subscription SET provider_subscription_id = 'sub_unmapped', row_version = row_version + 1 WHERE subscription_id = ?", + one.subscriptionId()))); + var duplicateTenant = request(first, UUID.randomUUID(), 1, null); + rejectSql( + "23514", + () -> + c.tx() + .executeWithoutResult( + s -> + insertBareOperation( + c, duplicateTenant, first, UUID.randomUUID(), UUID.randomUUID()))); + assertThat(indexDefinition(c, "uq_subscription_active_tenant")) + .contains("UNIQUE", "superseded_at IS NULL"); + assertThat( + c.repository() + .findCurrentByTenant(first.tenant()) + .orElseThrow() + .providerSubscriptionId()) + .isNull(); + assertThat( + c.repository() + .findCurrentByTenant(second.tenant()) + .orElseThrow() + .providerSubscriptionId()) + .isNull(); + } + + @Test + void + operationSubscriptionReservationAndOutboxCannotCommitPartiallyAndCrossRoleKeysCannotBeReused() { + Context c = context(); + Seed first = seed(c); + var created = create(c, request(first, UUID.randomUUID(), 1, null)); + Seed empty = seed(c); + var missingPair = request(empty, UUID.randomUUID(), 1, null); + rejectSql( + "23503", + () -> + c.tx() + .executeWithoutResult( + s -> + insertBareOperation( + c, missingPair, empty, UUID.randomUUID(), UUID.randomUUID()))); + assertThat(c.repository().findCreation(missingPair.requestId())).isEmpty(); + rejectSql( + "23505", + () -> + c.tx() + .executeWithoutResult( + s -> + insertBareOperation( + c, + request(empty, UUID.randomUUID(), 1, null), + empty, + created.cleanupProviderIdentity(), + UUID.randomUUID()))); + for (String table : + List.of( + "subscription_create_operations", + "subscription_create_outbox", + "subscription_create_provider_identities")) { + rejectSql("23514", () -> c.setup().execute("DELETE FROM " + table)); + rejectSql("23514", () -> c.setup().execute("TRUNCATE " + table + " CASCADE")); + } + rejectSql("23514", () -> c.setup().execute("DELETE FROM subscription")); + rejectSql("23514", () -> c.setup().execute("DELETE FROM subscription_instrument_reservations")); + rejectSql( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription_create_operations SET request_digest = request_digest")); + assertThat(count(c, "subscription_create_operations")).isOne(); + assertThat(count(c, "subscription_create_outbox")).isOne(); + } + + @Test + void + canceledCommitRequiresSeparateTerminalEvidenceAndExactInstrumentReleaseInTheSameTransaction() { + Context c = context(); + Seed seed = seed(c); + var creation = create(c, request(seed, UUID.randomUUID(), 1, null)); + rejectSql( + "23514", + () -> + c.tx() + .executeWithoutResult( + s -> { + c.repository().lockPendingForClaim(creation.requestId(), 1); + UUID resolution = UUID.randomUUID(); + c.dsl() + .execute( + "INSERT INTO subscription_provider_terminal_resolutions " + + "(resolution_id,request_id,subscription_id,cleanup_provider_identity,outcome,effective_at,evidence_digest) " + + "VALUES (?, ?, ?, ?, 'PROVIDER_ABSENT', ?::timestamptz, ?)", + resolution, + creation.requestId(), + creation.subscriptionId(), + creation.cleanupProviderIdentity(), + BOUNDARY, + DIGEST); + c.dsl() + .execute( + "UPDATE subscription SET status = 'canceled', terminal_resolution_id = ?, row_version = row_version + 1 WHERE subscription_id = ?", + resolution, + creation.subscriptionId()); + })); + assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().status()) + .isEqualTo("pending"); + assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); + controlledTerminalCleanup(c, creation); + rejectSql("23514", () -> controlledProviderHistory(c, creation, "sub_afterTerminalAbsence")); + assertThat(c.repository().lookupProviderId("sub_afterTerminalAbsence").disposition()) + .isEqualTo(MappingDisposition.UNRESOLVED); + } + + @Test + void terminalCleanupAfterWalletAdvanceReleasesOnlyItsOriginalReservationWithoutRewritingWallet() { + Context c = context(); + Seed first = seed(c); + var originalRequest = request(first, UUID.randomUUID(), 1, null); + var original = create(c, originalRequest); + var instruments = new AccountPaymentInstrumentRepository(c.dsl()); + var advancedWallet = + Objects.requireNonNull( + c.tx() + .execute( + s -> + instruments.recordAvailability( + new AccountPaymentInstrumentRepository.AvailabilityObservation( + UUID.randomUUID(), + first.instrument().instrumentUuid(), + c.account(), + 1, + AccountPaymentInstrumentRecord.State.ATTACHABLE, + first.instrument().display(), + "sha256:" + "b".repeat(64))))); + assertThat(advancedWallet.rowVersion()).isEqualTo(2); + Seed otherTenant = seed(c); + Seed sharedWallet = new Seed(otherTenant.tenant(), otherTenant.owner(), first.instrument()); + var independent = create(c, request(sharedWallet, UUID.randomUUID(), 2, null)); + assertThat(independent.paymentInstrumentId()).isEqualTo(original.paymentInstrumentId()); + var independentHold = + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT * FROM subscription_instrument_reservations WHERE request_id = ?", + independent.requestId())) + .intoMap(); + var walletHistory = + c.setup() + .fetch( + "SELECT * FROM account_payment_instrument_observations WHERE instrument_uuid = ? ORDER BY row_version", + original.paymentInstrumentId()) + .intoMaps(); + + // Controlled provider absence is the cleanup evidence, not a fresh provisioning claim or a + // rewrite of wallet currentness. The original reservation still records observed version 1. + UUID terminalResolution = controlledTerminalCleanup(c, original); + var releasedHold = + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT * FROM subscription_instrument_reservations WHERE request_id = ?", + original.requestId())) + .intoMap(); + assertThat(releasedHold.get("instrument_version")) + .isEqualTo(original.reservedInstrumentVersion()); + assertThat(releasedHold.get("terminal_resolution_id")).isEqualTo(terminalResolution); + assertThat(releasedHold.get("released_at")).isNotNull(); + var terminalReceipt = + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT * FROM subscription_provider_terminal_resolutions WHERE resolution_id = ?", + terminalResolution)) + .intoMap(); + assertThat(controlledTerminalCleanup(c, original)).isEqualTo(terminalResolution); + assertThat(create(c, originalRequest)).isEqualTo(original); + + // An old request/subscription tuple or the originally observed version cannot select the + // independent version-2 reservation. Nor may a stale caller rewrite its immutable identity. + c.tx() + .executeWithoutResult( + s -> { + assertThat( + c.dsl() + .execute( + "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = clock_timestamp() " + + "WHERE request_id = ? AND subscription_id = ? AND payment_instrument_id = ? AND instrument_version = ? AND released_at IS NULL", + terminalResolution, + independent.requestId(), + independent.subscriptionId(), + original.paymentInstrumentId(), + original.reservedInstrumentVersion())) + .isZero(); + assertThat( + c.dsl() + .execute( + "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = clock_timestamp() " + + "WHERE request_id = ? AND subscription_id = ? AND payment_instrument_id = ? AND instrument_version = ? AND released_at IS NULL", + terminalResolution, + original.requestId(), + independent.subscriptionId(), + original.paymentInstrumentId(), + independent.reservedInstrumentVersion())) + .isZero(); + }); + for (String assignment : + List.of( + "request_id = '" + original.requestId() + "'::uuid", + "subscription_id = '" + original.subscriptionId() + "'::uuid", + "instrument_version = " + original.reservedInstrumentVersion())) { + rejectSql( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription_instrument_reservations SET " + + assignment + + ", terminal_resolution_id = ?, released_at = clock_timestamp() WHERE request_id = ?", + terminalResolution, + independent.requestId())); + } + rejectSql( + "23505", + () -> + c.tx() + .executeWithoutResult( + s -> { + c.dsl() + .execute( + "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = clock_timestamp() WHERE request_id = ?", + terminalResolution, + independent.requestId()); + })); + assertThat( + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT * FROM subscription_instrument_reservations WHERE request_id = ?", + independent.requestId())) + .intoMap()) + .isEqualTo(independentHold); + assertThat(c.repository().findCurrentByTenant(otherTenant.tenant()).orElseThrow().status()) + .isEqualTo("pending"); + assertThat( + Objects.requireNonNull( + c.tx() + .execute( + s -> c.repository().lockPendingForClaim(independent.requestId(), 1))) + .subscriptionId()) + .isEqualTo(independent.subscriptionId()); + assertThat( + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT * FROM subscription_instrument_reservations WHERE request_id = ?", + original.requestId())) + .intoMap()) + .isEqualTo(releasedHold); + assertThat( + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT * FROM subscription_provider_terminal_resolutions WHERE resolution_id = ?", + terminalResolution)) + .intoMap()) + .isEqualTo(terminalReceipt); + assertThat(instruments.findByOwner(c.account(), original.paymentInstrumentId())) + .contains(advancedWallet); + assertThat( + c.setup() + .fetch( + "SELECT * FROM account_payment_instrument_observations WHERE instrument_uuid = ? ORDER BY row_version", + original.paymentInstrumentId()) + .intoMaps()) + .isEqualTo(walletHistory); + } + + @Test + void + providerHistoryAndTerminalEvidenceAreSeparateImmutableAndUnknownIdsNeverChooseCurrentAuthority() { + Context c = context(); + Seed seed = seed(c); + var creation = create(c, request(seed, UUID.randomUUID(), 1, null)); + assertThat(c.repository().lookupProviderId("sub_unknown").disposition()) + .isEqualTo(MappingDisposition.UNRESOLVED); + assertThat(count(c, "subscription_provider_history")).isZero(); + controlledProviderHistory(c, creation, "sub_original"); + assertThat(c.repository().lookupProviderId("sub_original").disposition()) + .isEqualTo(MappingDisposition.HISTORY_ONLY); + assertThat( + c.repository() + .findCurrentByTenant(seed.tenant()) + .orElseThrow() + .providerSubscriptionId()) + .isNull(); + c.tx() + .executeWithoutResult( + s -> + c.dsl() + .execute( + "UPDATE subscription SET provider_subscription_id = 'sub_original', row_version = row_version + 1 WHERE subscription_id = ?", + creation.subscriptionId())); + var mapped = c.repository().lookupProviderId("sub_original"); + assertThat(mapped.disposition()).isEqualTo(MappingDisposition.CURRENT_MAPPING); + assertThat(mapped.history().orElseThrow().providerOperationId()) + .isEqualTo(creation.subscriptionProvisioningRequestId()); + assertThat(mapped.terminalResolution()).isEmpty(); + assertThat(c.repository().lookupProviderId("sub_predecessorNotRecorded").disposition()) + .isEqualTo(MappingDisposition.UNRESOLVED); + rejectSql("23505", () -> controlledProviderHistory(c, creation, "sub_conflicting")); + rejectSql( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription SET provider_subscription_id = 'sub_guessed', row_version = row_version + 1 WHERE subscription_id = ?", + creation.subscriptionId())); + controlledTerminalCleanup(c, creation); + var terminal = c.repository().lookupProviderId("sub_original"); + assertThat(terminal.disposition()).isEqualTo(MappingDisposition.TERMINAL_HISTORY); + assertThat(terminal.terminalResolution().orElseThrow().cleanupProviderIdentity()) + .isEqualTo(creation.cleanupProviderIdentity()); + var canceled = c.repository().findCurrentByTenant(seed.tenant()).orElseThrow(); + create( + c, + request( + seed, + UUID.randomUUID(), + 1, + new ReplacementFence(creation.subscriptionId(), canceled.rowVersion()))); + var current = c.repository().findCurrentByTenant(seed.tenant()).orElseThrow(); + assertThat(current.providerSubscriptionId()).isNull(); + assertThat( + c.repository() + .lookupProviderId("sub_original") + .history() + .orElseThrow() + .subscriptionId()) + .isEqualTo(creation.subscriptionId()); + assertThat(c.repository().findCurrentByTenant(seed.tenant())).contains(current); + for (String table : + List.of( + "subscription_provider_history", + "subscription_provider_terminal_resolutions", + "subscription_current_observations")) { + rejectSql("23514", () -> c.setup().execute("DELETE FROM " + table)); + rejectSql("23514", () -> c.setup().execute("TRUNCATE " + table + " CASCADE")); + } + rejectSql( + "23514", () -> c.setup().execute("UPDATE subscription_provider_history SET role = role")); + rejectSql( + "23514", + () -> + c.setup() + .execute( + "UPDATE subscription_provider_terminal_resolutions SET outcome = outcome")); + rejectSql( + "23503", + () -> c.setup().execute("DELETE FROM accounts WHERE account_uuid = ?", c.account())); + } + + private static void advanceBeforeCreate( + Context c, AccountSubscriptionCreateRequest request, Runnable controlledAdvance) + throws Exception { + CountDownLatch advanced = new CountDownLatch(1); + CountDownLatch contenderStarted = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + var holderPid = new AtomicInteger(); + var contenderPid = new AtomicInteger(); + var executor = Executors.newFixedThreadPool(2); + try { + var holder = + executor.submit( + () -> + c.tx() + .executeWithoutResult( + s -> { + holderPid.set( + Objects.requireNonNull(c.dsl().fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + c.dsl() + .fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", + c.account()); + controlledAdvance.run(); + advanced.countDown(); + await(release); + })); + if (!advanced.await(5, TimeUnit.SECONDS)) { + // Expose a failed owner transaction instead of masking it as a coordination timeout. + holder.get(1, TimeUnit.SECONDS); + throw new AssertionError("Controlled owner advance did not reach its lock boundary"); + } + var contender = + executor.submit( + () -> { + // Classify rejections only after the original create transaction has rolled back. + try { + c.tx() + .executeWithoutResult( + s -> { + contenderPid.set( + Objects.requireNonNull(c.dsl().fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + contenderStarted.countDown(); + c.repository().retainPending(request); + }); + return "APPLIED"; + } catch (ConflictException conflict) { + return "CONFLICT"; + } catch (FenceRejectedException stale) { + return "FENCED"; + } + }); + assertThat(contenderStarted.await(5, TimeUnit.SECONDS)).isTrue(); + awaitBlocked(c, contenderPid.get(), holderPid.get()); + release.countDown(); + holder.get(15, TimeUnit.SECONDS); + assertThat(contender.get(15, TimeUnit.SECONDS)).isEqualTo("FENCED"); + } finally { + release.countDown(); + executor.shutdownNow(); + } + } + + private static void awaitBlocked(Context c, int waitingPid, int blockerPid) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + var observed = + Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT ? = ANY(pg_blocking_pids(?)) AS blocked", blockerPid, waitingPid), + "Exact PostgreSQL blocking identity readback required"); + if (Boolean.TRUE.equals(observed.get("blocked", Boolean.class))) { + return; + } + Thread.onSpinWait(); + } + throw new IllegalStateException( + "Subscription create did not block on the controlled Account owner transaction"); + } + + /** Controlled qualified-result shape only; no Stripe or lifecycle producer is claimed. */ + private static void controlledProviderHistory( + Context c, AccountSubscriptionCreationRecord creation, String providerId) { + c.tx() + .executeWithoutResult( + s -> + c.dsl() + .execute( + "INSERT INTO subscription_provider_history " + + "(provider_subscription_id,subscription_id,operation_kind,request_id,provider_operation_id,role,effective_at,evidence_digest) " + + "VALUES (?, ?, 'SUBSCRIPTION_PROVISIONING', ?, ?, 'canonical', ?::timestamptz, ?)", + providerId, + creation.subscriptionId(), + creation.requestId(), + creation.subscriptionProvisioningRequestId(), + BOUNDARY, + DIGEST)); + } + + /** + * Controlled SQL cleanup tuple; does not prove provider verification or a lifecycle outbox + * bridge. + */ + private static UUID controlledTerminalCleanup( + Context c, AccountSubscriptionCreationRecord creation) { + return Objects.requireNonNull( + c.tx() + .execute( + s -> { + // Cleanup is not a new provisioning claim. Lock the same sources without + // requiring + // the globally shared wallet to retain the original observed + // version/availability. + new AccountPaymentInstrumentRepository(c.dsl()) + .findByOwnerForUpdate( + creation.owner().accountUuid(), creation.paymentInstrumentId()) + .orElseThrow(); + c.dsl() + .fetchOne( + "SELECT * FROM account_tenant_billing_owners WHERE tenant_uuid = ? FOR UPDATE", + creation.tenantId()); + var current = + Objects.requireNonNull( + c.dsl() + .fetchOne( + "SELECT * FROM subscription WHERE subscription_id = ? AND tenant_id = ? AND creation_request_id = ? FOR UPDATE", + creation.subscriptionId(), + creation.tenantId(), + creation.requestId())); + var hold = + Objects.requireNonNull( + c.dsl() + .fetchOne( + "SELECT * FROM subscription_instrument_reservations WHERE request_id = ? AND subscription_id = ? AND payment_instrument_id = ? AND instrument_version = ? FOR UPDATE", + creation.requestId(), + creation.subscriptionId(), + creation.paymentInstrumentId(), + creation.reservedInstrumentVersion())); + if (hold.get("released_at") != null) { + UUID retainedResolution = hold.get("terminal_resolution_id", UUID.class); + assertThat(current.get("status", String.class)).isEqualTo("canceled"); + assertThat(current.get("terminal_resolution_id", UUID.class)) + .isEqualTo(retainedResolution); + var receipt = + Objects.requireNonNull( + c.dsl() + .fetchOne( + "SELECT * FROM subscription_provider_terminal_resolutions WHERE resolution_id = ? AND request_id = ? AND subscription_id = ? AND cleanup_provider_identity = ?", + retainedResolution, + creation.requestId(), + creation.subscriptionId(), + creation.cleanupProviderIdentity())); + assertThat(receipt.get("provider_subscription_id", String.class)) + .isEqualTo(current.get("provider_subscription_id", String.class)); + return retainedResolution; + } + UUID resolution = UUID.randomUUID(); + c.dsl() + .execute( + "INSERT INTO subscription_provider_terminal_resolutions " + + "(resolution_id,request_id,subscription_id,cleanup_provider_identity,provider_subscription_id,outcome,effective_at,evidence_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?)", + resolution, + creation.requestId(), + creation.subscriptionId(), + creation.cleanupProviderIdentity(), + current.get("provider_subscription_id", String.class), + current.get("provider_subscription_id") == null + ? "PROVIDER_ABSENT" + : "CANCELED", + BOUNDARY, + DIGEST); + assertThat( + c.dsl() + .execute( + "UPDATE subscription SET status = 'canceled', terminal_resolution_id = ?, row_version = row_version + 1 WHERE subscription_id = ? AND creation_request_id = ? AND row_version = ? AND status = 'pending'", + resolution, + creation.subscriptionId(), + creation.requestId(), + current.get("row_version", Long.class))) + .isOne(); + assertThat( + c.dsl() + .execute( + "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = clock_timestamp() WHERE request_id = ? AND subscription_id = ? AND payment_instrument_id = ? AND instrument_version = ? AND released_at IS NULL", + resolution, + creation.requestId(), + creation.subscriptionId(), + creation.paymentInstrumentId(), + creation.reservedInstrumentVersion())) + .isOne(); + return resolution; + })); + } + + private static void advanceWallet(Context c, UUID instrument, UUID changeRequest) { + c.dsl() + .execute( + "UPDATE payment_instrument SET row_version = row_version + 1, change_request_id = ?, evidence_digest = ? WHERE instrument_uuid = ?", + changeRequest, + DIGEST, + instrument); + } + + private static void insertBareOperation( + Context c, + AccountSubscriptionCreateRequest request, + Seed seed, + UUID createKey, + UUID cleanupKey) { + var quote = configuredPlans().resolve(request.planCode()); + insertBareOperationWithQuote( + c, request, seed, createKey, cleanupKey, quote, quote.payload(), quote.digest()); + } + + private static void insertBareOperationWithQuote( + Context c, + AccountSubscriptionCreateRequest request, + Seed seed, + UUID createKey, + UUID cleanupKey, + AccountHostingPlanQuote quote, + byte[] quotePayload, + String quoteDigest) { + var encoded = + AccountSubscriptionCreateDigest.encode( + request.tenantId(), + request.owner().accountUuid(), + request.planCode(), + request.paymentInstrumentId()); + c.dsl() + .execute( + "INSERT INTO subscription_create_operations (request_id,subscription_id,tenant_id,account_uuid,owner_version,owner_generation,actor_account_uuid,authorization_operation_id,authorization_digest,plan_code,payment_instrument_id,reserved_instrument_version,customer_provisioning_request_id,provider_customer_id,subscription_provisioning_request_id,cleanup_provider_identity,request_payload,request_digest,plan_quote_payload,plan_quote_digest,provider_price_id,provider_quantity,max_active_sessions,max_concurrent_game_instances,max_storage_bytes) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + request.requestId(), + UUID.randomUUID(), + request.tenantId(), + request.owner().accountUuid(), + request.owner().version(), + request.owner().generation(), + c.account(), + request.producer().authorizationOperationId(), + request.producer().authorizationDigest(), + request.planCode(), + request.paymentInstrumentId(), + request.instrumentVersion(), + seed.instrument().customerProvisioningRequestId(), + seed.instrument().providerCustomerId(), + createKey, + cleanupKey, + encoded.payload(), + encoded.digest(), + quotePayload, + quoteDigest, + quote.providerPriceId(), + quote.providerQuantity(), + quote.maxActiveSessions(), + quote.maxConcurrentGameInstances(), + quote.maxStorageBytes()); + } + + private static AccountSubscriptionCreationRecord create( + Context c, AccountSubscriptionCreateRequest request) { + return Objects.requireNonNull(c.tx().execute(s -> c.repository().retainPending(request))); + } + + private static String attemptCreate(Context c, AccountSubscriptionCreateRequest request) { + try { + create(c, request); + return "APPLIED"; + } catch (ConflictException conflict) { + return "CONFLICT"; + } catch (FenceRejectedException stale) { + return "FENCED"; + } + } + + private static AccountSubscriptionCreateRequest request( + Seed seed, UUID request, long instrumentVersion, ReplacementFence replacement) { + return new AccountSubscriptionCreateRequest( + request, + seed.tenant(), + seed.owner(), + "basic-hosting", + seed.instrument().instrumentUuid(), + instrumentVersion, + producer(seed.owner().accountUuid()), + replacement); + } + + private static ProducerEvidence producer(UUID account) { + return new ProducerEvidence(account, UUID.randomUUID(), DIGEST); + } + + private static Seed seed(Context c) { + UUID tenant = UUID.randomUUID(); + UUID creationRequest = UUID.randomUUID(); + UUID creationOperation = UUID.randomUUID(); + long gameRow = GAME_ROWS.incrementAndGet(); + String key = "game-" + gameRow; + String requestDigest = + GameTenantCreationDigest.requestDigest( + "prod", creationRequest, key, "Controlled tenant", "Storage proof only"); + var creation = + new FreshTenantCreationEvidence( + 1, + "prod", + creationRequest, + creationOperation, + requestDigest, + tenant, + gameRow, + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", + creationRequest, + creationOperation, + requestDigest, + tenant, + gameRow, + key, + "NEW_GAME_ROW")); + UUID authorityOperation = UUID.randomUUID(); + var creator = + new FreshTenantCreatorEvidence( + 1, + creation, + c.account(), + authorityOperation, + DIGEST, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, c.account(), authorityOperation, DIGEST)); + c.tx() + .executeWithoutResult( + s -> + new FreshTenantIdentityAssociationRepository(c.dsl(), "prod") + .importVerified(creation)); + var ownerResult = + Objects.requireNonNull( + c.tx() + .execute( + s -> + new AccountInitialTenantBillingOwnerRepository(c.dsl()) + .establishInitial( + new AccountInitialTenantBillingOwnerRepository.InitialRequest( + UUID.randomUUID(), creator, UUID.randomUUID(), 1, true)))); + var customers = new AccountBillingCustomerRepository(c.dsl()); + var customer = + Objects.requireNonNull( + c.tx() + .execute( + s -> + customers.retainIntent( + c.account(), UUID.randomUUID(), UUID.randomUUID()))) + .customer(); + if (customer.state() != AccountBillingCustomerRecord.State.CONFIRMED) { + var pending = customer; + customer = + Objects.requireNonNull( + c.tx() + .execute( + s -> + customers.recordObservation( + c.account(), + pending.customerProvisioningRequestId(), + pending.rowVersion(), + UUID.randomUUID(), + AccountBillingCustomerRecord.Observation.CONFIRMED, + "cus_" + c.account().toString().replace("-", ""), + DIGEST))); + } + var confirmed = customer; + var instrument = + Objects.requireNonNull( + c.tx() + .execute( + s -> + new AccountPaymentInstrumentRepository(c.dsl()) + .retainAttachment( + new Attachment( + UUID.randomUUID(), + UUID.randomUUID(), + c.account(), + confirmed.customerProvisioningRequestId(), + confirmed.providerCustomerId(), + "pm_" + UUID.randomUUID().toString().replace("-", ""), + AccountPaymentInstrumentRecord.State.ATTACHABLE, + new DisplayMetadata("visa", "4242", 12, 2030), + DIGEST)))); + return new Seed( + tenant, + new OwnerFence(c.account(), ownerResult.ownerVersion(), ownerResult.ownerGeneration()), + instrument); + } + + private static List race(Supplier left, Supplier right) throws Exception { + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + var first = + executor.submit( + () -> { + ready.countDown(); + await(start); + return left.get(); + }); + var second = + executor.submit( + () -> { + ready.countDown(); + await(start); + return right.get(); + }); + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + return List.of(first.get(15, TimeUnit.SECONDS), second.get(15, TimeUnit.SECONDS)); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Storage proof barrier timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Storage proof interrupted", interrupted); + } + } + + private static void rejectSql(String state, ThrowingCallable action) { + assertThatThrownBy(action) + .satisfies( + failure -> { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql) { + assertThat(sql.getSQLState()).isEqualTo(state); + return; + } + } + throw new AssertionError("Expected PostgreSQL invariant refusal", failure); + }); + } + + private static long count(Context c, String table) { + return Objects.requireNonNull(c.setup().fetchOne("SELECT count(*) FROM " + table)) + .get(0, Long.class); + } + + private static String indexDefinition(Context c, String name) { + return Objects.requireNonNull( + c.setup() + .fetchOne( + "SELECT indexdef FROM pg_indexes WHERE schemaname = current_schema() AND indexname = ?", + name)) + .get(0, String.class); + } + + private static FluentConfiguration configuration(Context c) { + return Flyway.configure() + .dataSource(c.source()) + .schemas(c.schema()) + .defaultSchema(c.schema()) + .placeholders(Map.of("serviceSchema", c.schema())) + .locations("classpath:db/migration", "classpath:db/migration/saga"); + } + + private static Context context() { + Context c = predecessor(); + configuration(c).target("1029").load().migrate(); + return c; + } + + private static Context predecessor() { + String schema = "subscription_intent_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + source.setSchema(schema); + DSLContext setup = DSL.using(source, SQLDialect.POSTGRES); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var tx = new TransactionTemplate(new DataSourceTransactionManager(source)); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + tx.setTimeout(10); + var empty = + new Context( + source, + schema, + setup, + dsl, + tx, + new AccountSubscriptionIntentRepository(dsl, configuredPlans()), + null); + configuration(empty).target("1026").load().migrate(); + var account = + Objects.requireNonNull( + setup.fetchOne( + "INSERT INTO accounts(username,email,password_hash) VALUES ('subscription-owner','owner@example.test','hash') RETURNING id, account_uuid")); + setup.execute( + "INSERT INTO subscription(id,account_id,plan_id,status,started_at,ended_at,tenant_id,entitlement_version,tenant_authority_generation) VALUES " + + "(91,?,'unqualified-active','active','2025-01-02 03:04:05.123456',NULL,7,19,?)," + + "(92,?,'retained-canceled','canceled',NULL,'2025-02-03 04:05:06.654321',7,21,?)", + account.get("id", Long.class), + UUID.randomUUID(), + account.get("id", Long.class), + UUID.randomUUID()); + return new Context( + source, + schema, + setup, + dsl, + tx, + empty.repository(), + account.get("account_uuid", UUID.class)); + } + + /** Controlled configuration only; not an installed live catalog or production price selection. */ + private static AccountHostingPlanCatalog configuredPlans() { + return new AccountHostingPlanCatalog( + List.of( + new AccountHostingPlanCatalog.ConfiguredPlan( + "basic-hosting", "price_controlledInitial", "1", "100", "2", "1048576"))); + } + + private record Seed(UUID tenant, OwnerFence owner, AccountPaymentInstrumentRecord instrument) {} + + private record Context( + DriverManagerDataSource source, + String schema, + DSLContext setup, + DSLContext dsl, + TransactionTemplate tx, + AccountSubscriptionIntentRepository repository, + UUID account) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java new file mode 100644 index 0000000000..965acade65 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java @@ -0,0 +1,350 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.sql.SQLException; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual Flyway/PostgreSQL source selection over committed demo and hosting owners. Enrollment and + * Stripe transport are controlled fixture inputs. No triggers are bypassed and no clock is changed; + * this does not qualify authenticated producers, live Stripe, public registration or admission. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountTenantAuthoritySourceSelectionPostgresIntegrationTest { + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void retainedPendingSubscriptionWithoutCommittedTenantSourceIsUnavailable() { + Context c = context(); + var f = c.fixture(); + assertThat(f.intents().findCurrentByTenant(f.tenantId())).isPresent(); + assertThatThrownBy(c::select).hasMessageContaining("Current tenant source is absent"); + assertThat(f.transport().reads()).isZero(); + assertThat( + Objects.requireNonNull( + f.dsl() + .fetchOne( + "SELECT count(*) FROM account_tenant_authority_source_records WHERE tenant_uuid = ?", + f.tenantId())) + .get(0, Long.class)) + .isZero(); + } + + @Test + void demoSelectionUsesExactCommittedBindingWhilePaidConfigurationIsRetained() { + Context c = context(); + var f = c.fixture(); + DemoTenantEntitlementSnapshot first = c.provisionDemo(null, true); + SourceSelection selected = c.select(); + assertThat(selected.kind()).isEqualTo(SourceKind.NON_PAID_DEMO); + assertThat(selected.checkpoint().tenantBillingEventId()).isEqualTo(first.eventId()); + assertThat(selected.checkpoint().tenantBillingEventDigest()).isEqualTo(first.eventDigest()); + assertThat(selected.checkpoint().eventId()).isEqualTo(first.tenantAuthorityEventId()); + assertThat(selected.checkpoint().eventDigest()).isEqualTo(first.tenantAuthorityEventDigest()); + assertCurrentCheckpoint(c, selected); + assertThat(f.intents().findCurrentByTenant(f.tenantId()).orElseThrow().status()) + .isEqualTo("pending"); + assertThat(f.transport().reads()).isZero(); + + // A genuine owner mutation changes the source; the earlier selected identity cannot follow it. + DemoTenantEntitlementSnapshot second = c.provisionDemo(first, false); + SourceSelection current = c.select(); + assertThat(current.kind()).isEqualTo(SourceKind.NON_PAID_DEMO); + assertThat(selected.matches(current.checkpoint())).isFalse(); + assertThat(current.checkpoint().tenantBillingSequence()) + .isEqualTo(first.tenantBillingSequence() + 1) + .isEqualTo(second.tenantBillingSequence()); + assertThatThrownBy(() -> f.transaction().execute(status -> c.demos().revalidate(first))) + .hasMessageContaining("changed after"); + assertThat( + f.transaction() + .execute(status -> c.demos().readCurrent(f.tenantId())) + .allowPublicJoin()) + .isFalse(); + assertCurrentCheckpoint(c, current); + assertThat(f.transport().reads()).isZero(); + } + + @Test + void paidCommitReplacesHeadWithoutDeletingOrSelectingTheRetainedDemoFamily() { + Context c = context(); + var f = c.fixture(); + DemoTenantEntitlementSnapshot demo = c.provisionDemo(null, true); + SourceSelection oldSelection = c.select(); + var retainedDemoRow = + Objects.requireNonNull( + f.dsl() + .fetchOne( + "SELECT row_to_json(e)::text FROM account_demo_tenant_entitlements e WHERE tenant_uuid = ?", + f.tenantId())); + assertThat(retainedDemoRow).isNotNull(); + String retainedDemo = retainedDemoRow.get(0, String.class); + var retainedDemoEventRow = + Objects.requireNonNull( + f.dsl() + .fetchOne( + "SELECT payload FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = ?", + f.tenantId(), + demo.tenantBillingSequence())); + assertThat(retainedDemoEventRow).isNotNull(); + byte[] retainedDemoEvent = retainedDemoEventRow.get(0, byte[].class); + + UUID paidRequest = c.activatePaid(); + int providerReads = f.transport().reads(); + SourceSelection paid = c.select(); + assertThat(paid.kind()).isEqualTo(SourceKind.PAID_HOSTING); + assertThat(paid.checkpoint().requestId()).isEqualTo(paidRequest); + assertThat(paid.checkpoint().tenantBillingSequence()) + .isEqualTo(demo.tenantBillingSequence() + 1); + assertThat(oldSelection.matches(paid.checkpoint())).isFalse(); + assertCurrentCheckpoint(c, paid); + // Source selection is only routing data; it does not make its own provider observation. + assertThat(f.transport().reads()).isEqualTo(providerReads); + var actualReceipt = f.service().readCurrent(f.tenantId()); + assertThat(paid.matches(actualReceipt.tenantAuthorityEvent())).isTrue(); + assertThat(paid.checkpoint().tenantBillingEventId()).isEqualTo(actualReceipt.billingEventId()); + assertThat(paid.checkpoint().tenantBillingEventDigest()) + .isEqualTo(actualReceipt.billingEventDigest()); + assertThat(f.transport().reads()).isEqualTo(providerReads + 1); + + assertThat( + Objects.requireNonNull( + f.dsl() + .fetchOne( + "SELECT row_to_json(e)::text FROM account_demo_tenant_entitlements e WHERE tenant_uuid = ?", + f.tenantId())) + .get(0, String.class)) + .isEqualTo(retainedDemo); + assertThat( + Objects.requireNonNull( + f.dsl() + .fetchOne( + "SELECT payload FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = ?", + f.tenantId(), + demo.tenantBillingSequence())) + .get(0, byte[].class)) + .isEqualTo(retainedDemoEvent); + assertThat(f.intents().findCurrentByTenant(f.tenantId()).orElseThrow().status()) + .isEqualTo("active"); + assertThatThrownBy(() -> f.transaction().execute(status -> c.demos().readCurrent(f.tenantId()))) + .hasMessageContaining("stale against Account's shared tenant authority generation"); + assertThat(c.select().kind()).isEqualTo(SourceKind.PAID_HOSTING); + } + + @Test + void immutableBillingReceiptAndHeadGuardsRejectMalformedOrMismatchingReplacement() { + Context c = context(); + var f = c.fixture(); + c.activatePaid(); + SourceSelection original = c.select(); + + // These corruptions cannot become committed source states under the production guards. + assertSqlState23514( + () -> + f.dsl() + .execute( + "UPDATE account_tenant_entitlement_outbox_events SET payload = ? WHERE tenant_uuid = ?", + "{\"schemaVersion\":\"unknown-source/v1\"}" + .getBytes(java.nio.charset.StandardCharsets.UTF_8), + f.tenantId())); + assertSqlState23514( + () -> + f.dsl() + .execute( + "UPDATE account_tenant_authority_source_records SET tenant_billing_event_digest = ? WHERE tenant_uuid = ?", + "sha256:" + "f".repeat(64), + f.tenantId())); + assertSqlState23514( + () -> + f.dsl() + .execute( + "UPDATE subscription_lifecycle_receipts SET receipt_payload = ? WHERE tenant_id = ?", + new byte[] {'{', '}'}, + f.tenantId())); + + SourceSelection unchanged = c.select(); + assertThat(unchanged.kind()).isEqualTo(SourceKind.PAID_HOSTING); + assertThat(original.matches(unchanged.checkpoint())).isTrue(); + assertCurrentCheckpoint(c, unchanged); + } + + private static void assertCurrentCheckpoint(Context c, SourceSelection selected) { + var f = c.fixture(); + var head = + f.dsl() + .fetchOne( + "SELECT * FROM account_tenant_authority_source_records WHERE tenant_uuid = ?", + f.tenantId()); + assertThat(head).isNotNull(); + assertThat(selected.checkpoint().eventId().toString()) + .isEqualTo(head.get("last_event_id", String.class)); + assertThat(selected.checkpoint().eventDigest()) + .isEqualTo(head.get("last_event_digest", String.class)); + assertThat(selected.checkpoint().tenantAuthorityGeneration()) + .isEqualTo(head.get("current_generation", Long.class)); + assertThat(selected.checkpoint().tenantAuthoritySourceVersion()) + .isEqualTo(head.get("current_source_version", Long.class)); + assertThat(selected.checkpoint().requestId()) + .isEqualTo(head.get("last_request_id", UUID.class)); + assertThat(selected.checkpoint().tenantBillingSequence()) + .isEqualTo(head.get("tenant_billing_sequence", Long.class)); + var checkpoint = + Objects.requireNonNull( + f.transaction() + .execute( + status -> + new AccountAuthorityOutboxRepository(f.dsl()) + .readCheckpoint(TenantAuthorityEventV1Codec.streamKey(f.tenantId())) + .orElseThrow())); + assertThat(selected.checkpoint().outboxSequence()).isEqualTo(checkpoint.outboxSequence()); + assertThat(selected.checkpoint().eventId().toString()).isEqualTo(checkpoint.sourceEventId()); + assertThat(selected.checkpoint().eventDigest()).isEqualTo(checkpoint.sourceEventDigest()); + var billing = + f.dsl() + .fetchOne( + "SELECT e.event_id, e.event_digest, s.last_sequence FROM account_tenant_entitlement_outbox_events e " + + "JOIN account_tenant_entitlement_outbox_streams s USING (tenant_uuid) " + + "WHERE e.tenant_uuid = ? AND e.tenant_billing_sequence = ?", + f.tenantId(), + selected.checkpoint().tenantBillingSequence()); + assertThat(billing).isNotNull(); + assertThat(selected.checkpoint().tenantBillingSequence()) + .isEqualTo(billing.get("last_sequence", Long.class)); + assertThat(selected.checkpoint().tenantBillingEventId()) + .isEqualTo(billing.get("event_id", UUID.class)); + assertThat(selected.checkpoint().tenantBillingEventDigest()) + .isEqualTo(billing.get("event_digest", String.class)); + } + + private static void assertSqlState23514(Runnable operation) { + RuntimeException failure = assertThrows(RuntimeException.class, operation::run); + Throwable current = failure; + while (current != null) { + if (current instanceof SQLException sql) { + assertThat(sql.getSQLState()).isEqualTo("23514"); + return; + } + current = current.getCause(); + } + throw new AssertionError("Expected PostgreSQL guard refusal", failure); + } + + private static Context context() { + String schema = "source_selection_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration", "classpath:db/migration/saga") + .load() + .migrate(); + var f = CanonicalHostingSubscriptionTestFixture.create(source); + var identities = new FreshTenantIdentityAssociationRepository(f.dsl(), "prod"); + var generations = new AccountAuthorityGenerationRepository(f.dsl()); + var billing = new AccountTenantEntitlementOutboxRepository(f.dsl()); + var events = + new AccountTenantAuthorityEventRepository( + f.dsl(), + new AccountAuthorityOutboxRepository(f.dsl()), + billing, + identities, + generations); + var demos = + new AccountDemoTenantEntitlementRepository( + f.dsl(), identities, generations, billing, events); + return new Context(f, events, demos); + } + + private record Context( + CanonicalHostingSubscriptionTestFixture.Fixture fixture, + AccountTenantAuthorityEventRepository events, + AccountDemoTenantEntitlementRepository demos) { + private SourceSelection select() { + return Objects.requireNonNull( + fixture + .transaction() + .execute(status -> events.readCurrentSourceSelection(fixture.tenantId()))); + } + + private DemoTenantEntitlementSnapshot provisionDemo( + DemoTenantEntitlementSnapshot prior, boolean publicJoin) { + return Objects.requireNonNull( + fixture + .transaction() + .execute( + status -> { + var source = + new FreshTenantIdentityAssociationRepository(fixture.dsl(), "prod") + .read(fixture.tenantId()) + .orElseThrow(); + return demos.provision( + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + fixture.tenantId(), + source.creationRequestId(), + source.requestDigest(), + prior == null ? null : prior.entitlementVersion(), + prior == null ? null : prior.tenantAuthorityGeneration(), + prior == null ? null : prior.tenantAuthoritySourceVersion(), + true, + publicJoin, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3, 1, 1024)), + source); + })); + } + + private UUID activatePaid() { + var claim = + fixture + .service() + .claimProvisioning(fixture.creation().requestId(), 1L, UUID.randomUUID()) + .claim(); + UUID requestId = UUID.randomUUID(); + assertThat( + fixture + .service() + .reconcile( + requestId, + fixture.creation().requestId(), + claim.subscriptionRowVersion(), + fixture.providerId(), + claim.attemptId()) + .outcome()) + .isEqualTo(Outcome.COMMITTED); + return requestId; + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java index d72151f370..5f80a35681 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java @@ -10,10 +10,14 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; @@ -27,6 +31,8 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository.Capture; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; @@ -36,7 +42,11 @@ import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.flywaydb.core.Flyway; @@ -300,6 +310,596 @@ void terminalJournalFailureRollsBackMembershipEventPairAndAuditTogether() { assertThat(operation.terminalProof()).isNull(); } + @Test + void activeJoinRetainsExactSnapshotWithoutAnotherEventOrAuditAndReplays() { + Fixture fixture = newFixture(); + var original = fixture.commitFirstJoin(); + String nextRequest = fixture.prepareAnotherJoin(); + var result = fixture.commitExistingJoin(nextRequest); + var replay = fixture.commitExistingJoin(nextRequest); + + assertThat(result.outcome()).isEqualTo("ALREADY_ACTIVE"); + assertThat(result.membershipId()).isEqualTo(original.membershipId()); + assertThat(result.membershipVersion()).isEqualTo(2L); + assertThat(result.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(result.terminalProof().eventSequence()).isEqualTo(1L); + assertThat(result.terminalProof().auditEventId()).isNull(); + assertThat(replay).isEqualTo(result); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isEqualTo(1L); + assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.dsl.execute( + "UPDATE account_join_operations SET outcome_membership_version = 3 WHERE request_id = ?", + nextRequest))) + .isInstanceOf(RuntimeException.class) + .rootCause() + .isInstanceOfSatisfying( + java.sql.SQLException.class, + failure -> { + assertThat(failure.getSQLState()).isEqualTo("23514"); + assertThat(failure.getMessage()) + .contains("Terminal canonical JOIN receipt is immutable"); + }); + } + + @Test + void nullCommittedOutcomeIsRejectedByTerminalReceiptShapeGuard() { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + String nextRequest = fixture.prepareAnotherJoin(); + + // Retain a valid current membership witness but omit only the required committed outcome. + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.dsl.execute( + """ + UPDATE account_join_operations pending + SET status = 'COMMITTED', outcome = NULL, + last_attempt_authority_availability = 'AVAILABLE', + membership_id = original.membership_id, + outcome_membership_version = original.outcome_membership_version, + outcome_membership_authority_generation = original.outcome_membership_authority_generation, + membership_authority_outbox_stream_key = original.membership_authority_outbox_stream_key, + membership_authority_outbox_sequence = original.membership_authority_outbox_sequence, + membership_authority_event_id = original.membership_authority_event_id, + membership_authority_event_digest = original.membership_authority_event_digest + FROM account_join_operations original + WHERE pending.request_id = ? AND original.request_id = ? + """, + nextRequest, + fixture.requestId))) + .isInstanceOf(RuntimeException.class) + .rootCause() + .isInstanceOfSatisfying( + java.sql.SQLException.class, + failure -> { + assertThat(failure.getSQLState()).isEqualTo("23514"); + assertThat(failure.getMessage()) + .contains("Canonical JOIN terminal receipt is incomplete or noncommitting"); + }); + + var committed = fixture.commitExistingJoin(nextRequest); + assertThat(committed.status()).isEqualTo("COMMITTED"); + assertThat(committed.outcome()).isEqualTo("ALREADY_ACTIVE"); + assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); + } + + @Test + void closingEnrollmentPreservesAnActiveMembersEventFreeJoinSnapshot() { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + fixture.inTransaction( + () -> { + var current = fixture.demoEntitlements.readCurrent(fixture.tenantUuid); + fixture.demoEntitlements.provision( + fixture.entitlementRequest(UUID.randomUUID(), current, false), + fixture.tenantEvidence); + return null; + }); + String requestId = fixture.prepareAnotherJoin(); + var result = fixture.commitExistingJoin(requestId); + assertThat(result.outcome()).isEqualTo("ALREADY_ACTIVE"); + assertThat(result.allowPublicJoin()).isFalse(); + assertThat(result.membershipVersion()).isEqualTo(2L); + assertThat(result.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isEqualTo(1L); + assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); + } + + @Test + void activeNonAdmittingSnapshotWithoutPlayerRoleRemainsSuccessfulAndUnchanged() { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + fixture.seedControlledMembershipSnapshot("ACTIVE", java.util.List.of()); + BrowserFacade browser = fixture.browserFacade(); + var selected = + browser + .service() + .listBootstrapRealms(browser.bootstrapToken(), "tenant", "world") + .getFirst(); + var request = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + selected.connectScopeId(), UUID.randomUUID().toString()); + var result = browser.service().joinPublicProduction(browser.bootstrapToken(), request); + var replay = browser.service().joinPublicProduction(browser.bootstrapToken(), request); + assertThat(result.success()).isTrue(); + assertThat(result.outcomeCode()).isEqualTo("ALREADY_ACTIVE"); + assertThat(result.gameplayAdmissionAllowed()).isFalse(); + assertThat(result.membershipVersion()).isEqualTo(3L); + assertThat(result.membershipAuthorityGeneration()).isEqualTo(2L); + assertThat(replay.gameplayAdmissionAllowed()).isFalse(); + assertThat(replay.replayed()).isTrue(); + var member = + fixture.inTransaction( + () -> + fixture + .memberships + .findFreshMembershipForUpdate( + fixture.account.getAccountUuid(), fixture.tenantUuid) + .orElseThrow()); + var roles = + fixture.inTransaction( + () -> + fixture + .roles + .findForCanonicalUpdate( + fixture.account.getAccountUuid(), + fixture.tenantUuid, + fixture.provenance, + member.getId(), + 3L) + .orElseThrow()); + assertThat(roles.roles()).isEmpty(); + assertThat(member.isGameplayAdmissionAllowed()).isFalse(); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isEqualTo(2L); + assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); + } + + @Test + void pendingSplitTransitionCannotBeReclassifiedAsAnEventFreeActiveJoin() { + Fixture fixture = newFixture(); + var checkpoint = fixture.writeAndPublish(); + assertThatThrownBy(() -> fixture.commitExistingJoin(fixture.requestId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("precommitted transition"); + var member = + fixture.inTransaction( + () -> + fixture + .memberships + .findFreshMembershipForUpdate( + fixture.account.getAccountUuid(), fixture.tenantUuid) + .orElseThrow()); + var proof = + new AccountJoinOperationRepository.CanonicalJoinTerminalProof( + checkpoint.outboxStreamKey(), + checkpoint.outboxSequence(), + checkpoint.sourceEventId(), + checkpoint.sourceEventDigest(), + null, + null, + null, + 1L, + member.getId(), + member.getMembershipVersion(), + member.getMembershipAuthorityGeneration()); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.operations.commitCanonicalJoin( + fixture.requestId, + fixture.scope, + fixture.callerBinding, + "ALREADY_ACTIVE", + proof))) + .isInstanceOf(RuntimeException.class) + .rootCause() + .isInstanceOfSatisfying( + java.sql.SQLException.class, + failure -> { + assertThat(failure.getSQLState()).isEqualTo("23514"); + assertThat(failure.getMessage()) + .contains( + "Canonical JOIN terminal receipt does not match committed owner evidence"); + }); + assertThat(fixture.countAll("account_audit_outbox")).isZero(); + assertThat( + fixture + .inTransaction( + () -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(fixture.requestId) + .orElseThrow()) + .status()) + .isEqualTo("PENDING"); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void committedJoinReplaysStoredEvidenceAfterLaterMembershipChanges(boolean alreadyActive) { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + String originalRequest = alreadyActive ? fixture.prepareAnotherJoin() : fixture.requestId; + var committed = fixture.commitExistingJoin(originalRequest); + assertThat(committed.outcome()).isEqualTo(alreadyActive ? "ALREADY_ACTIVE" : "JOINED"); + + // Controlled historical owner input, not proof of a production leave API. + fixture.seedControlledInactiveOwnerSnapshot(); + var tables = + java.util.List.of( + "account_join_operations", + "account_tenant_membership", + "account_tenant_membership_role_snapshots", + "account_membership_pair_authority", + "account_authority_outbox_events", + "account_authority_outbox_streams", + "account_audit_outbox"); + java.util.function.Supplier storedRows = + () -> + tables.stream() + .map( + table -> + fixture + .dsl + .fetch( + "SELECT xmin::text AS row_version, to_jsonb(t)::text AS row_data FROM " + + table + + " t ORDER BY to_jsonb(t)::text") + .intoMaps()) + .toList(); + var inactiveRows = storedRows.get(); + assertThat(fixture.commitExistingJoin(originalRequest)).isEqualTo(committed); + assertThat(storedRows.get()).isEqualTo(inactiveRows); + + // A real subsequent JOIN owner operation advances the event and restores membership. + var restored = fixture.commitExistingJoin(fixture.prepareAnotherJoin()); + assertThat(restored.terminalProof().eventSequence()).isEqualTo(3L); + assertThat(restored.membershipVersion()).isEqualTo(4L); + var restoredRows = storedRows.get(); + assertThat(fixture.commitExistingJoin(originalRequest)).isEqualTo(committed); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.terminalCoordinator.commitCanonicalJoin( + fixture.scope, originalRequest, "different-caller", null, null, null))) + .isInstanceOf(CanonicalJoinOperationConflictException.class); + assertThat(storedRows.get()).isEqualTo(restoredRows); + } + + @Test + void inactiveJoinRestoresOneVersionAndEventWithoutChangingIndependentGeneration() { + Fixture fixture = newFixture(); + var first = fixture.commitFirstJoin(); + fixture.seedControlledInactiveOwnerSnapshot(); + String restoreRequest = fixture.prepareAnotherJoin(); + var result = fixture.commitExistingJoin(restoreRequest); + var replay = fixture.commitExistingJoin(restoreRequest); + + assertThat(result.outcome()).isEqualTo("JOINED"); + assertThat(result.membershipId()).isEqualTo(first.membershipId()); + assertThat(result.membershipVersion()).isEqualTo(4L); + assertThat(result.membershipAuthorityGeneration()).isEqualTo(2L); + assertThat(result.terminalProof().eventSequence()).isEqualTo(3L); + assertThat(result.terminalProof().auditEventId()) + .isNotNull() + .isNotEqualTo(first.auditEventId()); + assertThat(replay).isEqualTo(result); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isEqualTo(3L); + assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(2L); + var member = + fixture.inTransaction( + () -> + fixture + .memberships + .findFreshMembershipForUpdate( + fixture.account.getAccountUuid(), fixture.tenantUuid) + .orElseThrow()); + assertThat(member.getLifecycleState()).isEqualTo("ACTIVE"); + assertThat(member.isGameplayAdmissionAllowed()).isTrue(); + } + + @Test + void restoreTerminalFailureRollsBackMemberRolesPairEventAndAudit() { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + fixture.seedControlledInactiveOwnerSnapshot(); + String restoreRequest = fixture.prepareAnotherJoin(); + fixture.dsl.execute( + "CREATE FUNCTION fail_restore_terminal() RETURNS trigger LANGUAGE plpgsql AS $$ " + + "BEGIN IF NEW.status = 'COMMITTED' THEN RAISE EXCEPTION 'restore terminal failure'; " + + "END IF; RETURN NEW; END $$"); + fixture.dsl.execute( + "CREATE TRIGGER fail_restore_terminal BEFORE UPDATE ON account_join_operations " + + "FOR EACH ROW EXECUTE FUNCTION fail_restore_terminal()"); + + assertThatThrownBy(() -> fixture.commitExistingJoin(restoreRequest)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("restore terminal failure"); + var member = + fixture.inTransaction( + () -> + fixture + .memberships + .findFreshMembershipForUpdate( + fixture.account.getAccountUuid(), fixture.tenantUuid) + .orElseThrow()); + assertThat(member.getLifecycleState()).isEqualTo("INACTIVE"); + assertThat(member.getMembershipVersion()).isEqualTo(3L); + assertThat(member.getMembershipAuthorityGeneration()).isEqualTo(2L); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isEqualTo(2L); + assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); + var operation = + fixture.inTransaction( + () -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(restoreRequest) + .orElseThrow()); + assertThat(operation.status()).isEqualTo("PENDING"); + assertThat(operation.terminalProof()).isNull(); + } + + @Test + void browserFacadeComposesRealV2ProducerReaderAndTerminalOwnersAndReplaysCommittedReceipt() { + Fixture fixture = newFixture(); + BrowserFacade browser = fixture.browserFacade(); + var realms = browser.service().listBootstrapRealms(browser.bootstrapToken(), "tenant", "world"); + var selected = realms.getFirst(); + String requestId = UUID.randomUUID().toString(); + var request = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + selected.connectScopeId(), requestId); + + var first = browser.service().joinPublicProduction(browser.bootstrapToken(), request); + var replay = browser.service().joinPublicProduction(browser.bootstrapToken(), request); + + assertThat(first.success()).isTrue(); + assertThat(first.outcomeCode()).isEqualTo("JOINED"); + assertThat(first.accountId()).isEqualTo(fixture.account.getAccountUuid().toString()); + assertThat(first.tenantId()).isEqualTo(fixture.tenantUuid); + assertThat(first.membershipVersion()).isEqualTo(2L); + assertThat(first.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(first.gameplayAdmissionAllowed()).isTrue(); + assertThat(first.replayed()).isFalse(); + assertThat(replay.success()).isTrue(); + assertThat(replay.replayed()).isTrue(); + assertThat(replay.membershipId()).isEqualTo(first.membershipId()); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isEqualTo(1L); + assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); + var stored = + fixture.inTransaction( + () -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow()); + assertThat(stored.status()).isEqualTo("COMMITTED"); + assertThat(stored.operationRepresentationVersion()).isEqualTo(2); + assertThat(stored.scopeEvidence().tenantUuid()).isEqualTo(fixture.tenantUuid); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource( + strings = {"COMMITTED", "FAILED_UNBOUND", "FAILED_BOUND"}) + void browserFacadeReplaysOperationFinishedAfterPreparation(String terminalState) { + Fixture fixture = newFixture(); + BrowserFacade browser = fixture.browserFacade(); + var selected = + browser + .service() + .listBootstrapRealms(browser.bootstrapToken(), "tenant", "world") + .getFirst(); + String requestId = UUID.randomUUID().toString(); + var request = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + selected.connectScopeId(), requestId); + var callerReads = new java.util.concurrent.atomic.AtomicInteger(); + var retained = + new java.util.concurrent.atomic.AtomicReference< + AccountJoinOperationRepository.CanonicalJoinOperationEvidence>(); + org.mockito.Mockito.when( + browser + .sessions() + .isAccountSessionActive(fixture.account.getId(), browser.bootstrapToken())) + .thenAnswer( + invocation -> { + // The second caller read occurs outside SQL, after preparation and immediately before + // the final transaction. Finish another exact attempt in this deterministic gap. + if (callerReads.incrementAndGet() == 2) { + if ("COMMITTED".equals(terminalState)) { + var first = + browser.service().joinPublicProduction(browser.bootstrapToken(), request); + assertThat(first.success()).isTrue(); + assertThat(first.replayed()).isFalse(); + } else { + fixture.inTransaction( + () -> { + fixture.operations.lockAccount(fixture.account.getId()); + var scope = + fixture + .connectScopes + .findCanonical(selected.connectScopeId()) + .orElseThrow(); + var pending = + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow(); + assertThat(pending.status()).isEqualTo("PENDING"); + if ("FAILED_BOUND".equals(terminalState)) { + var policy = fixture.demoEntitlements.readCurrent(fixture.tenantUuid); + fixture.operations.bindCanonicalPolicyEvidence( + requestId, + scope, + pending.callerBinding(), + policy.allowPublicJoin(), + policy.entitlementVersion()); + } + fixture.operations.finishCanonicalFailure( + requestId, scope, pending.callerBinding(), "CONNECT_SCOPE_MISMATCH"); + return null; + }); + } + retained.set( + fixture.inTransaction( + () -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow())); + } + return true; + }); + + var replay = browser.service().joinPublicProduction(browser.bootstrapToken(), request); + + assertThat(retained.get()).isNotNull(); + assertThat(replay.replayed()).isTrue(); + assertThat(replay.success()).isEqualTo("COMMITTED".equals(terminalState)); + assertThat(replay.outcomeCode()).isEqualTo(retained.get().outcome()); + assertThat( + fixture.inTransaction( + () -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow())) + .isEqualTo(retained.get()); + assertThat(fixture.countAll("account_audit_outbox")) + .isEqualTo("COMMITTED".equals(terminalState) ? 1L : 0L); + } + + @Test + void browserFacadeReplaysCommittedJoinProofAfterMembershipBecomesInactive() { + Fixture fixture = newFixture(); + BrowserFacade browser = fixture.browserFacade(); + var selected = + browser + .service() + .listBootstrapRealms(browser.bootstrapToken(), "tenant", "world") + .getFirst(); + String requestId = UUID.randomUUID().toString(); + var request = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + selected.connectScopeId(), requestId); + + var original = browser.service().joinPublicProduction(browser.bootstrapToken(), request); + fixture.seedControlledInactiveOwnerSnapshot(); + var replay = browser.service().joinPublicProduction(browser.bootstrapToken(), request); + + assertThat(original.success()).isTrue(); + assertThat(original.outcomeCode()).isEqualTo("JOINED"); + assertThat(original.membershipVersion()).isEqualTo(2L); + assertThat(original.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(original.gameplayAdmissionAllowed()).isTrue(); + assertThat(replay.success()).isTrue(); + assertThat(replay.outcomeCode()).isEqualTo(original.outcomeCode()); + assertThat(replay.membershipId()).isEqualTo(original.membershipId()); + assertThat(replay.membershipVersion()).isEqualTo(original.membershipVersion()); + assertThat(replay.membershipAuthorityGeneration()) + .isEqualTo(original.membershipAuthorityGeneration()); + assertThat(replay.gameplayAdmissionAllowed()).isFalse(); + assertThat(replay.replayed()).isTrue(); + + var currentMembership = + fixture.inTransaction( + () -> + fixture + .memberships + .findFreshMembershipForUpdate( + fixture.account.getAccountUuid(), fixture.tenantUuid) + .orElseThrow()); + assertThat(currentMembership.getLifecycleState()).isEqualTo("INACTIVE"); + assertThat(currentMembership.getMembershipVersion()).isEqualTo(3L); + assertThat(currentMembership.getMembershipAuthorityGeneration()).isEqualTo(2L); + assertThat(currentMembership.isGameplayAdmissionAllowed()).isFalse(); + } + + @Test + void directFacadeComposesItsOwnAuthenticatedProducerWithRealV2ReaderAndJoinOwners() { + Fixture fixture = newFixture(); + BrowserFacade composed = fixture.browserFacade(); + var target = composed.target(); + String requestId = UUID.randomUUID().toString(); + var caller = + new net.firedevops.firemud.accountservice.dto.DirectTextCallerContext( + fixture.account.getAccountUuid(), + fixture.tenantUuid, + target.realmId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + "2001", + requestId); + var selected = + new net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget( + fixture.tenantUuid, + target.realmId(), + target.worldSlug(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion()); + var peer = + new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( + "spiffe://firemud/ns/" + TEST_NAMESPACE + "/sa/game-session-service", + TEST_NAMESPACE, + "game-session-service"); + var context = + io.grpc.Context.ROOT.withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, peer); + context.run( + () -> { + var scope = composed.service().issueDirectTextConnectScope(caller, selected); + var request = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + scope.connectScopeId(), requestId); + var first = composed.service().joinPublicProductionFromGameSession(caller, request); + var replay = composed.service().joinPublicProductionFromGameSession(caller, request); + assertThat(first.success()).isTrue(); + assertThat(first.tenantId()).isEqualTo(fixture.tenantUuid); + assertThat(first.membershipVersion()).isEqualTo(2L); + assertThat(first.gameplayAdmissionAllowed()).isTrue(); + assertThat(replay.success()).isTrue(); + assertThat(replay.replayed()).isTrue(); + assertThat(replay.membershipId()).isEqualTo(first.membershipId()); + }); + org.mockito.Mockito.verifyNoInteractions(composed.sessions()); + assertThat( + fixture.count( + "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) + .isEqualTo(1L); + assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); + } + private Fixture newFixture() { return new Fixture(newTestContext()); } @@ -408,7 +1008,7 @@ private Account createAccount() { input.setUsername("canonical-join-" + suffix); input.setEmail("canonical-join-" + suffix + "@example.test"); input.setPasswordHash("integration-fixture-hash"); - input.setRole("player"); + // Player role belongs to the canonical tenant membership, not global Account authority. return inTransaction(() -> accounts.save(input)); } @@ -453,6 +1053,11 @@ private DemoTenantEntitlementSnapshot provisionCurrentTenantEntitlement() { private DemoTenantEntitlementRequest entitlementRequest( UUID requestId, DemoTenantEntitlementSnapshot current) { + return entitlementRequest(requestId, current, true); + } + + private DemoTenantEntitlementRequest entitlementRequest( + UUID requestId, DemoTenantEntitlementSnapshot current, boolean allowPublicJoin) { return new DemoTenantEntitlementRequest( requestId, tenantUuid, @@ -462,7 +1067,7 @@ private DemoTenantEntitlementRequest entitlementRequest( current == null ? null : current.tenantAuthorityGeneration(), current == null ? null : current.tenantAuthoritySourceVersion(), true, - true, + allowPublicJoin, true, true, new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); @@ -491,6 +1096,583 @@ private AccountJoinOperationRepository.CanonicalJoinTerminalProof commitFirstJoi () -> terminalCoordinator.commitCanonicalFirstJoin(scope, requestId, callerBinding)); } + private String prepareAnotherJoin() { + String nextRequest = UUID.randomUUID().toString(); + inTransaction( + () -> { + operations.lockAccount(account.getId()); + operations.insertCanonicalIntent(nextRequest, scope, callerBinding); + var policy = demoEntitlements.readCurrent(tenantUuid); + operations.bindCanonicalPolicyEvidence( + nextRequest, + scope, + callerBinding, + policy.allowPublicJoin(), + policy.entitlementVersion()); + return null; + }); + return nextRequest; + } + + private AccountJoinOperationRepository.CanonicalJoinOperationEvidence commitExistingJoin( + String nextRequest) { + return inTransaction( + () -> + terminalCoordinator.commitCanonicalJoin( + scope, nextRequest, callerBinding, null, null, null)); + } + + private BrowserFacade browserFacade() { + var jwt = + new net.firedevops.firemud.common.security.JwtUtil( + "controlled-browser-facade-integration-signing-key-0123456789", 300000L); + var sessions = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.service.session.SessionService.class); + String bootstrap = + jwt.generateToken( + account.getAccountUuid().toString(), + 300000L, + Map.of( + "aud", + "player-bootstrap", + "accountId", + account.getAccountUuid().toString(), + "jti", + UUID.randomUUID().toString())); + org.mockito.Mockito.when(sessions.isAccountSessionActive(account.getId(), bootstrap)) + .thenReturn(true); + var targets = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.client + .CanonicalGameplayAdmissionDecisionReadClient.class); + var target = controlledPublishedTarget(); + org.mockito.Mockito.when( + targets.listVisiblePublicProductionAdmissionTargets( + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var request = + new net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + invocation.getArgument(0, UUID.class), TEST_NAMESPACE); + return net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, java.util.List.of(target))); + }); + org.mockito.Mockito.when( + targets.resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var selector = + invocation.getArgument( + 0, + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector + .class); + return net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + selector, + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + selector, target)); + }); + // The protected client is the controlled upstream boundary in this Account SQL composition; + // this fixture does not claim physical GS publication or World lifecycle validation. + org.mockito.Mockito.when( + targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var selector = + invocation.getArgument( + 0, + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .Request.class); + var published = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + .class); + org.mockito.Mockito.when(published.selector()).thenReturn(selector); + org.mockito.Mockito.when(published.currentTarget()).thenReturn(target); + return published; + }); + var hosting = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountHostingSubscriptionLifecycleRepository.class); + var observer = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver.class); + var manager = Objects.requireNonNull(transaction.getTransactionManager()); + var clock = java.time.Clock.systemUTC(); + var properties = new net.firedevops.firemud.accountservice.config.AccountTokenProperties(); + properties.setConnectScopeExpirationMs(120000L); + var entitlementOwner = + new net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner( + tenantAuthorityEvents, + new net.firedevops.firemud.accountservice.service + .AccountHostingSubscriptionLifecycleService(hosting, observer, manager), + demoEntitlements, + manager, + clock); + var producerOwner = + new net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner( + new net.firedevops.firemud.accountservice.service.session + .AccountPlayerBootstrapCallerVerifier(jwt, accounts, sessions), + targets, + entitlementOwner, + accounts, + memberships, + freshTenants, + tenantAuthorityEvents, + connectScopes, + jwt, + properties, + clock, + manager, + TEST_NAMESPACE); + var service = + new net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl( + accounts, + generations, + sourceEvidence, + outbox, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountPasswordResetOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountLogoutAllOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.service + .AccountPasswordResetDraftSourceChangeRepository.class), + auditOutbox, + operations, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountEmailLoginChallengeRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository + .class), + memberships, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + new net.firedevops.firemud.accountservice.config.MailProperties(), + properties, + new net.firedevops.firemud.common.security.JwtAuthProperties(), + jwt, + sessions, + manager); + service.setCanonicalPublicRealmScopeOwner(producerOwner); + service.setCanonicalScopeConsumers( + new net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader( + jwt, connectScopes, manager, clock), + targets, + tenantAuthorityEvents, + demoEntitlements, + hosting, + observer, + terminalCoordinator, + TEST_NAMESPACE, + clock); + return new BrowserFacade(service, bootstrap, target, sessions); + } + + /** + * Protected GS transport remains a controlled owner response; Account SQL/JWT owners are real. + */ + private net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target + controlledPublishedTarget() { + UUID version = UUID.randomUUID(); + String digest = "a".repeat(64); + String initial = UUID.randomUUID().toString(); + var holdRequest = + new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request( + TEST_NAMESPACE, + tenantUuid, + scope.worldSlug(), + scope.realmId(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + version, + 1L, + initial, + digest, + net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold + .InitialAdmissionOrigin.NO_PRIOR_POINTER, + scope.catalogRevision(), + null); + var hold = + new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity( + holdRequest, UUID.randomUUID(), UUID.randomUUID()); + return new net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target( + TEST_NAMESPACE, + "tenant", + tenantUuid, + scope.worldSlug(), + "World", + scope.realmId(), + scope.realmSlug(), + "Production", + 11L, + 44L, + scope.playableStateNamespaceId(), + "SHARED", + scope.gameInstanceId(), + version, + 1L, + scope.catalogRevision(), + scope.pointerVersion(), + digest, + 1L, + initial, + digest, + net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec + .OriginKind.NO_PRIOR_POINTER, + null, + hold.holdId(), + hold.holdFence(), + hold.holdBindingDigest(), + 1L, + "sha256:" + digest, + net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec + .OwnerProofOutcome.COMMITTED, + false, + java.time.Instant.now(), + "PRESEEDED_ONLY"); + } + + /** Controlled retained INACTIVE input; this fixture does not claim a production leave owner. */ + private void seedControlledInactiveOwnerSnapshot() { + seedControlledMembershipSnapshot("INACTIVE", java.util.List.of("player")); + } + + /** Controlled owner snapshot; no leave, creator grant or lifecycle mutation API is claimed. */ + @SuppressWarnings("unchecked") + private void seedControlledMembershipSnapshot( + String lifecycle, java.util.List currentRoles) { + // The existing draft source-change owner requires a physical READ_COMMITTED connection. + var historicalTransaction = new TransactionTemplate(transaction.getTransactionManager()); + historicalTransaction.setPropagationBehavior( + org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW); + historicalTransaction.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + historicalTransaction.execute( + status -> { + operations.lockAccount(account.getId()); + var member = + memberships + .findFreshMembershipForUpdate(account.getAccountUuid(), tenantUuid) + .orElseThrow(); + var generation = + generations.read( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantUuid)); + // This is controlled historical input, not an implemented leave/role-removal owner. + // One atomic invalidating transaction advances the closed Account source and fence; + // the member generation then advances under that same fence without inventing an + // Account event or weakening the V40 deferred source/fence checks. + var accountBefore = + sourceEvidence.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, account.getAccountUuid()); + commitControlledClosedAccountSecurityChange(accountBefore.account()); + assertThat( + dsl.execute( + "UPDATE account_authority_generations SET generation = generation + 1, " + + "source_version = source_version + 1, updated_at = CURRENT_TIMESTAMP " + + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? AND tenant_uuid = ? " + + "AND generation = ? AND source_version = ?", + account.getAccountUuid(), + tenantUuid, + generation.generation(), + generation.sourceVersion())) + .isEqualTo(1); + var next = generations.read(generation.scope()); + var authority = + generations.readCompositeSnapshot( + ACCOUNT_ISSUER, + account.getAccountUuid(), + java.util.List.of(tenantUuid), + java.util.List.of(tenantUuid)); + var accountSource = + sourceEvidence.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, account.getAccountUuid()); + assertThat(next.generation()).isEqualTo(generation.generation() + 1L); + assertThat(next.sourceVersion()).isEqualTo(generation.sourceVersion() + 1L); + assertThat(next.issuanceFence().value()) + .isEqualTo(generation.issuanceFence().value() + 1L); + assertThat(next.issuanceFence().sourceVersion()) + .isEqualTo(generation.issuanceFence().sourceVersion() + 1L); + assertThat(accountSource.issuanceFence()).isEqualTo(next.issuanceFence()); + assertThat(accountSource.account().generation()) + .isEqualTo(accountBefore.account().generation() + 1L); + assertThat(accountSource.account().sourceVersion()) + .isEqualTo(accountBefore.account().sourceVersion() + 1L); + assertThat(accountSource.account().checkpoint().sequence()) + .isEqualTo(accountBefore.account().checkpoint().sequence() + 1L); + var tenantSource = tenantAuthorityEvents.readCurrentByTenant(tenantUuid); + var prior = pairs.readForUpdate(account.getAccountUuid(), tenantUuid).orElseThrow(); + long nextMembershipVersion = member.getMembershipVersion() + 1L; + long nextEventSequence = prior.eventSequence() + 1L; + var previousEvent = + outbox.findEvent(membershipStream(), prior.eventSequence()).orElseThrow(); + var json = tools.jackson.databind.json.JsonMapper.builder().build(); + Map event = + json.readValue( + new String(previousEvent.payload(), StandardCharsets.UTF_8), Map.class); + String inactiveRequest = "controlled-inactive-" + UUID.randomUUID(); + event.remove("eventDigest"); + event.put("eventId", UUID.randomUUID().toString()); + event.put("requestId", inactiveRequest); + event.put("outboxSequence", Long.toString(nextEventSequence)); + event.put("membershipLifecycleState", lifecycle); + event.put("roles", currentRoles); + event.put( + "membershipVersion", + Map.of(tenantUuid.toString(), Long.toString(nextMembershipVersion))); + event.put("membershipAuthorityGeneration", Long.toString(next.generation())); + Map tuple = new java.util.LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", Long.toString(authority.issuer().generation())); + tuple.put( + "accountAuthorityGeneration", Long.toString(authority.account().generation())); + tuple.put( + "tenantAuthorityGeneration", + Map.of( + tenantUuid.toString(), + Long.toString(authority.tenants().getFirst().generation()))); + tuple.put( + "membershipAuthorityGeneration", + Map.of(tenantUuid.toString(), Long.toString(next.generation()))); + tuple.put("privateRealmGrantVersions", java.util.List.of()); + var cutoff = accountSource.account().accountSecurityCutoff().orElseThrow(); + tuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence())); + tuple.put( + "tenantBillingCutoff", + Map.of( + tenantUuid.toString(), + Map.of( + "tenantAuthorityGeneration", + Long.toString(tenantSource.tenantAuthorityGeneration()), + "tenantBillingSequence", + Long.toString(tenantSource.tenantBillingSequence()), + "outboxStreamKey", tenantSource.outboxStreamKey(), + "outboxSequence", Long.toString(tenantSource.outboxSequence())))); + event.put("authorityTuple", tuple); + event.put("issuanceFence", Long.toString(next.issuanceFence().value())); + event.put("gameplayAdmissionAllowed", false); + event.put("callerBoundAuthorityInvalidated", true); + var sealed = MembershipAuthorityEventV1Codec.seal(event); + var appended = + outbox.append( + membershipStream(), + inactiveRequest, + sequence -> { + if (sequence != nextEventSequence) + throw new IllegalStateException("Controlled inactive sequence changed"); + return new AccountAuthorityOutboxRepository.EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + assertThat( + dsl.execute( + "UPDATE account_tenant_membership SET lifecycle_state = ?, gameplay_admission_allowed = FALSE, " + + "membership_version = ?, membership_authority_generation = ? WHERE id = ?", + lifecycle, + nextMembershipVersion, + next.generation(), + member.getId())) + .isEqualTo(1); + var inactive = + memberships + .findCanonicalMembershipForUpdate(account.getAccountUuid(), tenantUuid) + .orElseThrow(); + roles.replaceCanonical( + inactive, + account.getAccountUuid(), + tenantUuid, + provenance, + nextMembershipVersion, + currentRoles); + assertThat( + dsl.execute( + "UPDATE account_membership_pair_authority SET membership_version = ?, membership_authority_generation = ?, " + + "last_event_sequence = ?, last_event_id = ?, last_event_digest = ?, last_transition_invalidated = TRUE " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + nextMembershipVersion, + next.generation(), + appended.outboxSequence(), + appended.eventId(), + appended.eventDigest(), + account.getAccountUuid(), + tenantUuid)) + .isEqualTo(1); + return null; + }); + } + + /** + * Controlled sole-writer composition of the existing closed security-state operation. The + * correlation bytes are fixture input, not authenticated permission or a runtime producer. Keep + * the source change, exact receipt, event and head in the enclosing historical transaction. + */ + private void commitControlledClosedAccountSecurityChange( + AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence currentSource) { + var current = accounts.findByIdForUpdate(account.getId()).orElseThrow(); + var roleSource = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT global_roles, global_role_source_version FROM account_global_role_sources " + + "WHERE account_uuid = ? FOR SHARE", + account.getAccountUuid())); + long roleVersion = + Objects.requireNonNull(roleSource.get("global_role_source_version", Long.class)); + var before = + new AccountState( + current.isEmailVerified(), + AccountLoginAuthModes.read(current.getLoginAuthModes()).stream() + .map(Enum::name) + .sorted() + .toList(), + java.util.Arrays.stream(roleSource.get("global_roles", String[].class)) + .sorted() + .toList(), + current.getLifecycleState().name()); + var after = + new AccountState( + !before.emailVerified(), + before.loginAuthModes(), + before.globalRoles(), + before.lifecycleState()); + var sourceState = generations.read(currentSource.scope()); + String stream = currentSource.checkpoint().outboxStreamKey(); + long checkpointSequence = currentSource.checkpoint().sequence(); + byte[] checkpointPayload = + checkpointSequence == 0L + ? new byte[0] + : outbox.findEvent(stream, checkpointSequence).orElseThrow().payload(); + UUID securityRequest = UUID.randomUUID(); + byte[] correlation = + ("{\"actorAccountUuid\":\"" + + account.getAccountUuid() + + "\",\"ownerEvidenceDigest\":\"sha256:" + + "a".repeat(64) + + "\",\"ownerOperationId\":\"" + + securityRequest + + "\",\"schemaVersion\":\"account-security-state-caller-correlation/v1\"}") + .getBytes(StandardCharsets.UTF_8); + var request = + new AccountSecurityStateMutationRequest( + securityRequest, + account.getAccountUuid(), + correlation, + sourceState.generation(), + sourceState.sourceVersion(), + AccountSecurityStateOperationRepository.detectedKinds(before, after), + after); + var draft = + new Capture( + current.getId(), + current.getAccountUuidProvenance(), + before, + sourceState, + checkpointSequence, + checkpointPayload, + roleVersion, + null); + byte[] captureBytes = AccountSecurityStateOperationRepository.captureBytes(request, draft); + var source = + new SourceEvidence( + SourceKind.ACCOUNT, + account.getAccountUuid().toString(), + Long.toString(sourceState.generation()), + Long.toString(sourceState.sourceVersion()), + stream, + Long.toString(checkpointSequence), + captureBytes); + var change = new SourceChange(UUID.randomUUID(), java.util.List.of(source), captureBytes); + var capture = + new Capture( + draft.accountId(), + draft.provenance(), + before, + sourceState, + checkpointSequence, + checkpointPayload, + roleVersion, + change); + var fences = new DraftAuthorizationFenceRepository(dsl); + var securityOperations = new AccountSecurityStateOperationRepository(dsl); + assertThat(fences.requestSourceChange(change)).isTrue(); + assertThat(securityOperations.claim(request, capture).claimed()).isTrue(); + assertThat(fences.sourceMutationPermitted(change)).isTrue(); + var advanced = + sourceEvidence.prepareClosedAccountAdvance(account.getAccountUuid(), currentSource); + assertThat( + dsl.execute( + "UPDATE accounts SET email_verified = ? WHERE account_uuid = ?", + after.emailVerified(), + account.getAccountUuid())) + .isEqualTo(1); + var event = + outbox.append( + stream, + securityRequest.toString(), + sequence -> { + var sealed = + AccountSecurityStateAuthorityEventV1Codec.seal( + AccountSecurityStateMutationRequest.eventPreimage( + securityRequest, + account.getAccountUuid(), + Long.toString(advanced.generation()), + Long.toString(advanced.sourceVersion()), + Long.toString(sequence), + request.mutationKinds(), + after)); + return new AccountAuthorityOutboxRepository.EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + fences.markSourceCommitted(change); + var committed = securityOperations.complete(request, event, advanced, roleVersion); + assertThat(committed.receipt().orElseThrow().event()).isEqualTo(event); + assertThat(committed.capture().sourceChange().canonicalBytes()) + .isEqualTo(change.canonicalBytes()); + assertThat(fences.readSourceChange(change).status()).isEqualTo("SOURCE_COMMITTED"); + } + private long membershipId() { return membershipId == null ? -1L : membershipId; } @@ -574,4 +1756,12 @@ private static long positiveRandomLong() { } private record TestContext(DSLContext dsl, TransactionTemplate transaction) {} + + private record BrowserFacade( + net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl service, + String bootstrapToken, + net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec + .Target + target, + net.firedevops.firemud.accountservice.service.session.SessionService sessions) {} } 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 new file mode 100644 index 0000000000..aedb15b4be --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java @@ -0,0 +1,399 @@ +package integration.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verifyNoInteractions; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import org.flywaydb.core.Flyway; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Physical Account transaction and real SDK decoding against a controlled local Stripe transport. + * Tenant/creator/billing setup and the caller/scope are controlled; no authenticated public caller, + * real Stripe, World hold, protected admission transport, custody or runtime activation is proved. + */ +class AccountPaidCanonicalFirstJoinPostgresIntegrationTest { + private static final String PREFIX = "paid_first_join_"; + private static final String CALLER = "controlled-paid-join-caller"; + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + private final Set schemas = ConcurrentHashMap.newKeySet(); + + @BeforeAll + static void start() { + POSTGRES.start(); + } + + @AfterAll + static void stop() { + POSTGRES.stop(); + } + + @AfterEach + void dropOwnedSchemas() { + var jdbc = new JdbcTemplate(POSTGRES.dataSource()); + for (String schema : schemas) { + if (!schema.startsWith(PREFIX) || !schema.matches("[a-z][a-z0-9_]{0,62}")) + throw new IllegalStateException("Refusing unowned schema cleanup"); + jdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + schemas.clear(); + } + + @Test + void paidJoinCommitsOnePlayerEventAuditAndReceiptThenExactlyReplaysWithoutProviderIo() { + Context c = context(false); + int reads = c.hosting.transport().reads(); + var first = c.commit(c.observed); + var replay = c.commit(c.observed); + assertThat(replay).isEqualTo(first); + assertThat(c.hosting.transport().reads()).isEqualTo(reads); + assertThat(c.scope.accountId()).isNotEqualTo(c.hosting.accountUuid()); + var retained = + c.hosting.transaction().execute(status -> c.outbox.findEvent(c.stream(), 1L).orElseThrow()); + var event = + MembershipAuthorityEventV1Codec.verify( + new String(Objects.requireNonNull(retained).payload(), StandardCharsets.UTF_8)); + assertThat(event.accountId()).isEqualTo(c.scope.accountId().toString()); + assertThat(event.authorityTuple().tenantBillingCutoff()).isPresent(); + assertThat(event.authorityTuple().tenantAuthorityGeneration()) + .containsKey(c.hosting.tenantId().toString()); + assertThat(c.count("account_tenant_membership")).isEqualTo(1); + assertThat(c.count("account_tenant_membership_role_snapshots")).isEqualTo(1); + assertThat(c.count("account_audit_outbox")).isEqualTo(1); + assertThat(c.operation().status()).isEqualTo("COMMITTED"); + assertThat(c.operation().terminalProof()).isEqualTo(first); + } + + @Test + void providerFactsChangedBeforeCommitRollbackAllStagedWritesThenSameOriginalCanRecover() { + Context c = context(false); + var original = c.operation(); + c.hosting.providerStatus("canceled"); + var contradictory = c.hosting.observer().observe(c.fence.binding()); + assertThatThrownBy(() -> c.commit(contradictory)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ENTITLEMENT_UNAVAILABLE: provider facts differ from the committed receipt"); + verifyNoInteractions(c.demos); + c.assertRolledBack(original); + c.hosting.providerStatus("active"); + var recovered = c.hosting.observer().observe(c.fence.binding()); + var committed = c.commit(recovered); + assertThat(committed.entitlementVersion()).isEqualTo(original.entitlementVersion()); + assertThat(c.count("account_tenant_membership")).isEqualTo(1); + assertThat(c.count("account_audit_outbox")).isEqualTo(1); + } + + @Test + void changedOperationPolicyCannotCommitAgainstAnOlderPaidReceipt() { + Context c = context(true); + var original = c.operation(); + assertThatThrownBy(() -> c.commit(c.observed)) + .hasMessageContaining("exact current public-join entitlement"); + c.assertRolledBack(original); + } + + @Test + void expiredPaidReceiptIsUnavailableAndNeverSelectsDemo() { + Context c = context(false); + var original = c.operation(); + c.hosting.clock().advance(Duration.ofHours(2)); + var freshSdkResult = c.hosting.observer().observe(c.fence.binding()); + assertThatThrownBy(() -> c.commit(freshSdkResult)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ENTITLEMENT_UNAVAILABLE: current receipt is expired or inconsistent"); + verifyNoInteractions(c.demos); + c.assertRolledBack(original); + } + + @Test + 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); + })) + .hasMessageContaining("controlled final paid JOIN commit refusal"); + c.assertRolledBack(original); + } + + private Context context(boolean wrongPolicy) { + String schema = PREFIX + UUID.randomUUID().toString().replace("-", ""); + schemas.add(schema); + var source = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + return new Context(CanonicalHostingSubscriptionTestFixture.create(source), wrongPolicy); + } + + private static final class Context { + private final CanonicalHostingSubscriptionTestFixture.Fixture hosting; + private final AccountJoinOperationRepository operations; + private final AccountAuthorityOutboxRepository outbox; + private final AccountDemoTenantEntitlementRepository demos; + private final AccountMembershipPairAuthorityRepository pairs; + private final AccountCanonicalFirstJoinTerminalCoordinator coordinator; + private final CanonicalJoinScopeV2 scope; + private final String requestId = UUID.randomUUID().toString(); + private final ReadFence fence; + private final StripeHostingSubscriptionObserver.Result observed; + + private Context(CanonicalHostingSubscriptionTestFixture.Fixture hosting, boolean wrongPolicy) { + this.hosting = hosting; + var claim = + hosting + .service() + .claimProvisioning(hosting.creation().requestId(), 1, UUID.randomUUID()) + .claim(); + var committed = + hosting + .service() + .reconcile( + UUID.randomUUID(), + hosting.creation().requestId(), + claim.subscriptionRowVersion(), + hosting.providerId(), + claim.attemptId()); + assertThat(committed.outcome()) + .isEqualTo( + net.firedevops.firemud.accountservice.repository + .AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED); + hosting.transaction().setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + var dsl = hosting.dsl(); + var accounts = new AccountRepository(dsl); + var fresh = new FreshTenantIdentityAssociationRepository(dsl, "prod"); + pairs = new AccountMembershipPairAuthorityRepository(dsl); + var members = new AccountTenantMembershipRepository(dsl, accounts, fresh, pairs); + var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + var generations = new AccountAuthorityGenerationRepository(dsl); + outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + var billing = new AccountTenantEntitlementOutboxRepository(dsl); + var tenantEvents = + new AccountTenantAuthorityEventRepository(dsl, outbox, billing, fresh, generations); + demos = + spy( + new AccountDemoTenantEntitlementRepository( + dsl, fresh, generations, billing, tenantEvents)); + var scopes = + new AccountConnectScopeRepository( + dsl, + new AccountTenantIdentityResolver( + mock(ApprovedLegacyTenantAssociationRepository.class), "prod"), + fresh); + operations = new AccountJoinOperationRepository(dsl, scopes); + var producer = + new AccountMembershipAuthorityEventProducer( + operations, + accounts, + pairs, + members, + roles, + generations, + outbox, + sources, + tenantEvents, + demos); + coordinator = + new AccountCanonicalFirstJoinTerminalCoordinator( + accounts, + operations, + members, + roles, + outbox, + pairs, + new AccountAuditOutboxRepository(dsl), + producer); + Account input = new Account(); + input.setUsername("paid-player-" + UUID.randomUUID()); + input.setEmail("paid-player-" + UUID.randomUUID() + "@example.test"); + input.setPasswordHash("controlled-hash"); + // Player role belongs to the canonical tenant membership, not global Account authority. + Account player = + Objects.requireNonNull(hosting.transaction().execute(status -> accounts.save(input))); + var now = hosting.clock().instant(); + scope = + new CanonicalJoinScopeV2( + "controlled-paid-scope-" + UUID.randomUUID(), + player.getAccountUuid(), + hosting.tenantId(), + UUID.randomUUID(), + "tenant", + "world", + "production", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 7, + 3, + now.toString(), + 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); + }); + fence = + Objects.requireNonNull( + hosting + .transaction() + .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)); + }); + } + + private AccountJoinOperationRepository.CanonicalJoinTerminalProof commit( + StripeHostingSubscriptionObserver.Result result) { + return Objects.requireNonNull( + hosting + .transaction() + .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(); + })); + } + + private String stream() { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + scope.accountId() + + "/" + + scope.tenantId(); + } + + private int count(String table) { + return hosting.dsl().fetchCount(DSL.table(table)); + } + + private void assertRolledBack( + AccountJoinOperationRepository.CanonicalJoinOperationEvidence original) { + assertThat(operation()).isEqualTo(original); + assertThat(count("account_tenant_membership")).isZero(); + assertThat(count("account_tenant_membership_role_snapshots")).isZero(); + assertThat(count("account_audit_outbox")).isZero(); + var checkpoint = hosting.transaction().execute(status -> outbox.readCheckpoint(stream())); + assertThat(checkpoint).isEmpty(); + var pair = + hosting + .transaction() + .execute(status -> pairs.readForUpdate(scope.accountId(), scope.tenantId())); + assertThat(pair).isEmpty(); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java new file mode 100644 index 0000000000..9c5f6a9b38 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java @@ -0,0 +1,329 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountTenantOperationEntitlementOwner.Request; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real Account SQL/current-source readers and real Stripe SDK over controlled read-only transport. + * Enrollment inputs and provider transport are controlled; no mTLS, registration, live Stripe, + * player producer/consumer, durable evaluation replay, or capacity-commit proof is claimed. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountTenantOperationEntitlementOwnerPostgresIntegrationTest { + private static final String WORLD = "spiffe://firemud/ns/prod/sa/world-management-service"; + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void reusedAccountFixtureKeepsConfirmedCustomerAndObservationHistoryUnchanged() { + var first = context().fixture(); + Account existing = new Account(); + existing.setId(first.accountId()); + existing.setAccountUuid(first.accountUuid()); + var customerBefore = + first + .dsl() + .fetch("SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM billing_customer t") + .intoMaps(); + var observationsBefore = + first + .dsl() + .fetch( + "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM account_billing_customer_observations t") + .intoMaps(); + assertThat( + java.util.Objects.requireNonNull( + first.dsl().fetchOne("SELECT row_version FROM billing_customer")) + .get(0, Long.class)) + .isGreaterThan(1L); + + var second = + CanonicalHostingSubscriptionTestFixture.create( + java.util.Objects.requireNonNull(first.jdbc().getDataSource()), existing); + + assertThat(second.accountUuid()).isEqualTo(first.accountUuid()); + assertThat(second.tenantId()).isNotEqualTo(first.tenantId()); + assertThat(second.creation().providerCustomerId()) + .isEqualTo(first.creation().providerCustomerId()); + assertThat( + first + .dsl() + .fetch( + "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM billing_customer t") + .intoMaps()) + .isEqualTo(customerBefore); + assertThat( + first + .dsl() + .fetch( + "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM account_billing_customer_observations t") + .intoMaps()) + .isEqualTo(observationsBefore); + } + + @Test + void paidUsesActualReceiptSdkAndAuthorityCheckpointWithFreshEvaluationOfSameSnapshot() { + Context c = context(); + var f = c.fixture(); + var claim = + f.service().claimProvisioning(f.creation().requestId(), 1, UUID.randomUUID()).claim(); + var committed = + f.service() + .reconcile( + UUID.randomUUID(), + f.creation().requestId(), + claim.subscriptionRowVersion(), + f.providerId(), + claim.attemptId()); + assertThat(committed.outcome()).isEqualTo(Outcome.COMMITTED); + int beforeReads = f.transport().reads(); + UUID requestId = UUID.randomUUID(); + var first = c.owner().evaluatePaid(new Request(f.tenantId(), requestId, WORLD)); + f.clock().advance(java.time.Duration.ofSeconds(30)); + var second = c.owner().evaluatePaid(new Request(f.tenantId(), requestId, WORLD)); + assertThat(f.transport().reads()).isEqualTo(beforeReads + 2); + assertThat(first.fields()) + .containsEntry("sourceKind", "PAID_HOSTING") + .containsEntry("subscriptionStatus", "active") + .containsEntry("provisioningStatus", null) + .containsEntry("allowNewInstanceStarts", true) + .containsEntry("callerWorkload", WORLD) + .containsEntry("requestId", requestId.toString()); + assertThat(first.fields().get("snapshotIdentity")) + .isEqualTo(second.fields().get("snapshotIdentity")); + assertThat(first.fields().get("evaluationIdentity")) + .isNotEqualTo(second.fields().get("evaluationIdentity")); + assertThat(java.time.Instant.parse((String) second.fields().get("evaluatedAt"))) + .isAfter(java.time.Instant.parse((String) first.fields().get("evaluatedAt"))); + assertThat(first.fields()) + .doesNotContainKeys("callerAccountId", "issuer", "accountId", "verifiedConnectScopeId"); + assertThat(first.fields().get("quotas")) + .isEqualTo( + Map.of( + "maxActiveSessions", + "100", + "maxConcurrentGameInstances", + "2", + "maxStorageBytes", + "1048576")); + assertActualTenantCheckpoint(c, first); + assertThat(RuntimeTenantOperationEntitlementEvidence.parseCanonical(first.canonicalBytes())) + .isEqualTo(first); + + f.providerStatus("canceled"); + assertThatThrownBy( + () -> c.owner().evaluatePaid(new Request(f.tenantId(), UUID.randomUUID(), WORLD))) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + } + + @Test + void captureRunsInsideFinalWritableTransactionAndFailureRollsBackCapturedSql() { + Context c = context(); + var f = c.fixture(); + var claim = + f.service().claimProvisioning(f.creation().requestId(), 1, UUID.randomUUID()).claim(); + var committed = + f.service() + .reconcile( + UUID.randomUUID(), + f.creation().requestId(), + claim.subscriptionRowVersion(), + f.providerId(), + claim.attemptId()); + assertThat(committed.outcome()).isEqualTo(Outcome.COMMITTED); + String marker = "capture_marker_" + UUID.randomUUID().toString().replace("-", ""); + AtomicInteger captures = new AtomicInteger(); + assertThatThrownBy( + () -> + f.service() + .readCurrentAndCapture( + f.tenantId(), + receipt -> { + captures.incrementAndGet(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat( + TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + f.dsl().execute("CREATE TABLE " + marker + " (id bigint)"); + throw new IllegalStateException("controlled capture rollback"); + })) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE") + .hasCauseInstanceOf(IllegalStateException.class) + .hasRootCauseMessage("controlled capture rollback"); + assertThat(captures).hasValue(1); + assertThat(f.dsl().fetchSingle("SELECT to_regclass(?)::text", marker).get(0, String.class)) + .isNull(); + } + + @Test + void pendingDoesNotBecomePositiveAndExplicitDemoUsesOnlyItsActualCurrentOwner() { + Context c = context(); + var f = c.fixture(); + assertThatThrownBy( + () -> c.owner().evaluatePaid(new Request(f.tenantId(), UUID.randomUUID(), WORLD))) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + assertThatThrownBy( + () -> c.owner().evaluateDemo(new Request(f.tenantId(), UUID.randomUUID(), WORLD))) + .isInstanceOf(RuntimeException.class); + var tenantSources = new FreshTenantIdentityAssociationRepository(f.dsl(), "prod"); + var committed = + f.transaction() + .execute( + status -> { + var source = tenantSources.read(f.tenantId()).orElseThrow(); + return c.demos() + .provision( + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + f.tenantId(), + source.creationRequestId(), + source.requestDigest(), + null, + null, + null, + true, + false, + true, + false, + new DemoTenantEntitlementRequest.Quotas(3, 1, 500)), + source); + }); + assertThat(committed).isNotNull(); + int beforeReads = f.transport().reads(); + var evaluated = c.owner().evaluateDemo(new Request(f.tenantId(), UUID.randomUUID(), WORLD)); + assertThat(evaluated.fields()) + .containsEntry("sourceKind", "NON_PAID_DEMO") + .containsEntry("subscriptionStatus", null) + .containsEntry("provisioningStatus", null) + .containsEntry("gameplayAvailable", true) + .containsEntry("allowPublicJoin", false) + .containsEntry("allowNewGameplayBindings", true) + .containsEntry("allowNewInstanceStarts", false); + assertActualTenantCheckpoint(c, evaluated); + assertThat(f.transport().reads()).isEqualTo(beforeReads); + assertThatThrownBy( + () -> c.owner().evaluatePaid(new Request(f.tenantId(), UUID.randomUUID(), WORLD))) + .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); + } + + @Test + void wrongWorkloadNamespaceAndPlayerRequestsFailBeforeSourceReads() { + Context c = context(); + var f = c.fixture(); + assertThatThrownBy( + () -> + c.owner() + .evaluatePaid( + new Request( + f.tenantId(), + UUID.randomUUID(), + "spiffe://firemud/ns/another/sa/world-management-service"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new Request( + f.tenantId(), + UUID.randomUUID(), + "spiffe://firemud/ns/prod/sa/game-session-service")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(new UUID(0L, 0L), UUID.randomUUID(), WORLD)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(f.transport().reads()).isZero(); + } + + @SuppressWarnings("unchecked") + private static void assertActualTenantCheckpoint( + Context c, RuntimeTenantOperationEntitlementEvidence value) { + var expected = + c.fixture() + .transaction() + .execute( + status -> + new AccountAuthorityOutboxRepository(c.fixture().dsl()) + .readCheckpoint( + TenantAuthorityEventV1Codec.streamKey(c.fixture().tenantId())) + .orElseThrow()); + assertThat(expected).isNotNull(); + var actual = (List>) value.fields().get("outboxCheckpoints"); + assertThat(actual) + .containsExactly( + Map.of( + "outboxStreamKey", + expected.outboxStreamKey(), + "outboxSequence", + Long.toString(expected.outboxSequence()), + "sourceEventId", + expected.sourceEventId(), + "sourceEventDigest", + expected.sourceEventDigest())); + } + + private static Context context() { + String schema = "tenant_operation_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration", "classpath:db/migration/saga") + .load() + .migrate(); + var f = CanonicalHostingSubscriptionTestFixture.create(source); + var identities = new FreshTenantIdentityAssociationRepository(f.dsl(), "prod"); + var generations = new AccountAuthorityGenerationRepository(f.dsl()); + var billing = new AccountTenantEntitlementOutboxRepository(f.dsl()); + var tenantEvents = + new AccountTenantAuthorityEventRepository( + f.dsl(), + new AccountAuthorityOutboxRepository(f.dsl()), + billing, + identities, + generations); + var demos = + new AccountDemoTenantEntitlementRepository( + f.dsl(), identities, generations, billing, tenantEvents); + var owner = + new AccountTenantOperationEntitlementOwner( + f.service(), demos, new DataSourceTransactionManager(source), f.clock(), "prod"); + return new Context(f, demos, owner); + } + + private record Context( + CanonicalHostingSubscriptionTestFixture.Fixture fixture, + AccountDemoTenantEntitlementRepository demos, + AccountTenantOperationEntitlementOwner owner) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java new file mode 100644 index 0000000000..5a122c2d0b --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java @@ -0,0 +1,587 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture.Fixture; +import java.nio.file.Path; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.Status; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Outcome; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.TransitionResult; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture.IssuedAccount; +import net.firedevops.firemud.accountservice.service.session.AccountHostingSubscriptionTerminalResolutionService.Input; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Coupled genuine Account issuance/current actor, primary authentication and PostgreSQL + * cancellation proof. Policy/signer platform inputs and Stripe transport remain controlled. + * Physical Redis primary/replica AOF acknowledgement executes; no deployed custody, provider + * cancellation, public registration, transfer, provider absence or runtime activation is + * established. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest { + private static final String PASSWORD = "test-only-terminal-resolution-password"; + private static final String OTP = "test-only-terminal-resolution-otp"; + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("terminal-resolution-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "terminal-resolution-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void actualAccountAndFreshOtpCommitOneAtomicCancellationAndAuthenticatedReplay() + throws Exception { + try (var accountOwners = accountOwners()) { + var failed = failedHosting(accountOwners); + var issued = failed.issued(); + var hosting = failed.hosting(); + var actor = issued.actors().authenticateAccount(issued.compact()); + var issuance = + hosting + .dsl() + .fetchSingle( + "SELECT * FROM account_control_ui_issuance_operations WHERE operation_id = ?", + actor.issuanceOperationId()); + assertThat(issuance.get("authorization_scope", String.class)).isEqualTo("ACCOUNT"); + assertThat(issuance.get("tenant_uuid", UUID.class)).isNull(); + assertThat(issuance.get("account_uuid", UUID.class)).isEqualTo(hosting.accountUuid()); + assertThat(issuance.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(issuance.get("token_hash", String.class)).isEqualTo(actor.tokenHash()); + assertThat(hosting.accountId()).isEqualTo(issued.account().getId()); + assertThat(hosting.accountUuid()).isEqualTo(actor.accountId()); + assertThat( + hosting + .dsl() + .fetchSingle( + "SELECT count(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_uuid = ?", + hosting.accountId(), + hosting.tenantId()) + .get(0, Long.class)) + .isZero(); + + issued.sources().installGlobalOtp(issued.account(), OTP); + long auditBefore = count(hosting, "account_audit_outbox"); + int readsBefore = hosting.transport().reads(); + var result = resolve(failed, issued.account().getEmail(), OTP); + assertThat(result.outcome()).isEqualTo(Outcome.COMMITTED); + assertThat(hosting.transport().reads()).isEqualTo(readsBefore + 1); + assertThat(issued.sources().challenges.findByAccountId(hosting.accountId())).isEmpty(); + assertCommittedCancellation(failed, result); + assertThat(count(hosting, "account_audit_outbox")).isEqualTo(auditBefore + 1); + assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); + assertThat(hosting.service().readCurrent(hosting.tenantId()).subscriptionStatus()) + .isEqualTo(Status.CANCELED); + + var committed = financialImage(failed); + int readsAfterCommit = hosting.transport().reads(); + // Exact replay authenticates the real current actor but needs neither OTP nor another SDK + // read. + assertThat(service(failed).resolve(issued.compact(), null, null, failed.input())) + .isEqualTo(result); + assertThat(hosting.transport().reads()).isEqualTo(readsAfterCommit); + assertThat(financialImage(failed)).isEqualTo(committed); + assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); + } + } + + @Test + void wrongPrimaryCredentialRetainsFinancialFenceAndUnconsumedOtp() throws Exception { + try (var accountOwners = accountOwners()) { + var failed = failedHosting(accountOwners); + var issued = failed.issued(); + var challenge = issued.sources().installGlobalOtp(issued.account(), OTP); + var before = financialImage(failed); + assertThatThrownBy( + () -> resolve(failed, issued.account().getEmail(), "wrong-test-credential")) + .isInstanceOfSatisfying( + AuthenticationException.class, + failure -> assertThat(failure.getCode()).isEqualTo("AUTH_INVALID_CREDENTIALS")); + assertThat(financialImage(failed)).isEqualTo(before); + assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); + // Real failed-login accounting may advance; it must not consume the challenge. + assertThat(issued.sources().challenges.findByAccountId(failed.hosting().accountId())) + .isPresent() + .get() + .extracting(value -> value.getId()) + .isEqualTo(challenge.getId()); + } + } + + @Test + void lateBillingSqlFailureRollsBackCancellationAndOtpThenSameOtpSucceeds() throws Exception { + try (var accountOwners = accountOwners()) { + var failed = failedHosting(accountOwners); + var issued = failed.issued(); + var hosting = failed.hosting(); + var challenge = issued.sources().installGlobalOtp(issued.account(), OTP); + var before = financialImage(failed); + hosting + .dsl() + .execute( + "CREATE FUNCTION reject_resolution_billing() RETURNS trigger LANGUAGE plpgsql AS $$ " + + "BEGIN RAISE EXCEPTION 'controlled resolution billing failure' USING ERRCODE = '23514'; END; $$"); + hosting + .dsl() + .execute( + "CREATE TRIGGER reject_resolution_billing BEFORE INSERT ON account_tenant_entitlement_outbox_events " + + "FOR EACH ROW EXECUTE FUNCTION reject_resolution_billing()"); + try { + assertThatThrownBy(() -> resolve(failed, issued.account().getEmail(), OTP)) + .hasStackTraceContaining("controlled resolution billing failure"); + assertThat(financialImage(failed)).isEqualTo(before); + assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); + assertThat(issued.sources().challenges.findByAccountId(hosting.accountId())) + .contains(challenge); + } finally { + hosting + .dsl() + .execute( + "DROP TRIGGER reject_resolution_billing ON account_tenant_entitlement_outbox_events"); + hosting.dsl().execute("DROP FUNCTION reject_resolution_billing()"); + } + var result = resolve(failed, issued.account().getEmail(), OTP); + assertCommittedCancellation(failed, result); + assertThat(issued.sources().challenges.findByAccountId(hosting.accountId())).isEmpty(); + assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); + } + } + + @Test + void missingFailedOperationCopyRejectsBeforeCurrentCasAndRollsBackAuditJournalAndOtp() + throws Exception { + try (var accountOwners = accountOwners()) { + var failed = failedHosting(accountOwners); + var issued = failed.issued(); + var hosting = failed.hosting(); + var challenge = issued.sources().installGlobalOtp(issued.account(), OTP); + var before = financialImage(failed); + hosting + .dsl() + .execute( + "CREATE FUNCTION suppress_resolution_operation() RETURNS trigger LANGUAGE plpgsql AS $$ " + + "BEGIN RETURN NULL; END; $$"); + hosting + .dsl() + .execute( + "CREATE TRIGGER suppress_resolution_operation BEFORE INSERT ON subscription_lifecycle_operations " + + "FOR EACH ROW WHEN (NEW.request_id = '" + + failed.input().resolutionRequestId() + + "'::uuid) EXECUTE FUNCTION suppress_resolution_operation()"); + try { + // A controlled row trigger makes INSERT...SELECT affect zero rows despite the locked + // original still existing. The exact copy must fail before the current-row CAS. + assertThatThrownBy(() -> resolve(failed, issued.account().getEmail(), OTP)) + .isExactlyInstanceOf(FenceRejectedException.class) + .hasMessage("Terminal resolution exact failed-operation copy rejected"); + assertThat(financialImage(failed)).isEqualTo(before); + assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); + assertThat(issued.sources().challenges.findByAccountId(hosting.accountId())) + .contains(challenge); + } finally { + hosting + .dsl() + .execute( + "DROP TRIGGER suppress_resolution_operation ON subscription_lifecycle_operations"); + hosting.dsl().execute("DROP FUNCTION suppress_resolution_operation()"); + } + var result = resolve(failed, issued.account().getEmail(), OTP); + assertCommittedCancellation(failed, result); + assertThat(issued.sources().challenges.findByAccountId(hosting.accountId())).isEmpty(); + assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); + } + } + + @Test + void genericAccountAuthorityAdvanceDuringSdkReadMakesSourceUnavailableAndKeepsOtp() + throws Exception { + try (var accountOwners = accountOwners()) { + var failed = failedHosting(accountOwners); + var issued = failed.issued(); + var hosting = failed.hosting(); + var challenge = issued.sources().installGlobalOtp(issued.account(), OTP); + var before = financialImage(failed); + var generations = new AccountAuthorityGenerationRepository(hosting.dsl()); + var authorityBefore = + issued + .sources() + .tx(() -> generations.read(AuthorityScope.account(hosting.accountUuid()))); + hosting + .transport() + .duringRead( + () -> + issued + .sources() + .tx( + () -> { + var account = + issued + .sources() + .accounts + .findById(hosting.accountId()) + .orElseThrow(); + account.setRole("admin"); + // Generic authority events lack the closed operation receipt required + // by current-source readback, so this advance must fail closed there. + return issued.sources().accounts.save(account); + })); + assertThatThrownBy(() -> resolve(failed, issued.account().getEmail(), OTP)) + .isExactlyInstanceOf(SourceEvidenceUnavailableException.class) + .hasMessage("Account authority source evidence is unavailable or inconsistent"); + var authorityAfter = + issued + .sources() + .tx(() -> generations.read(AuthorityScope.account(hosting.accountUuid()))); + assertThat(authorityAfter.generation()).isGreaterThan(authorityBefore.generation()); + assertThat(authorityAfter.issuanceFence().value()) + .isGreaterThan(authorityBefore.issuanceFence().value()); + // The deliberately changed ACCOUNT authority/source rows are outside this financial image. + assertThat(financialImage(failed)).isEqualTo(before); + assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); + assertThat(issued.sources().challenges.findByAccountId(hosting.accountId())) + .contains(challenge); + } + } + + @Test + void otherCertifiedAccountsFreshOtpCannotAuthorizeBillingOwnerAndConsumptionRollsBack() + throws Exception { + try (var accountOwners = accountOwners()) { + var failed = failedHosting(accountOwners); + var other = accountOwners.issueCertifiedAccount("test-only-other-account-password"); + assertThat(other.actors().authenticateAccount(other.compact()).accountId()) + .isNotEqualTo(failed.hosting().accountUuid()); + var challenge = other.sources().installGlobalOtp(other.account(), OTP); + var before = financialImage(failed); + assertThatThrownBy(() -> resolve(failed, other.account().getEmail(), OTP)) + .isInstanceOf(FenceRejectedException.class) + .hasMessageContaining("another Account"); + assertThat(financialImage(failed)).isEqualTo(before); + assertThat(failureImage(failed)).isEqualTo(failed.failureImage()); + assertThat(other.sources().challenges.findByAccountId(other.account().getId())) + .contains(challenge); + } + } + + private AccountControlUiOriginalOrderFixture accountOwners() throws Exception { + return new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary); + } + + private static FailedHosting failedHosting(AccountControlUiOriginalOrderFixture accountOwners) { + var issued = accountOwners.issueCertifiedAccount(PASSWORD); + var hosting = + CanonicalHostingSubscriptionTestFixture.create( + Objects.requireNonNull(issued.sources().manager.getDataSource()), issued.account()); + var claim = + Objects.requireNonNull( + hosting + .service() + .claimProvisioning(hosting.creation().requestId(), 1, UUID.randomUUID()) + .claim()); + UUID failedRequest = UUID.randomUUID(); + hosting.providerStatus("incomplete"); + Outcome outcome = null; + // This shared fixture owns a four-attempt/three-stall bound; retain one original operation. + for (int attempt = 0; attempt < 4; attempt++) { + outcome = + hosting + .service() + .reconcile( + failedRequest, + hosting.creation().requestId(), + claim.subscriptionRowVersion(), + hosting.providerId(), + claim.attemptId()) + .outcome(); + if (outcome == Outcome.TERMINAL_FAILURE) break; + assertThat(outcome).isEqualTo(Outcome.RECONCILING); + hosting.clock().advance(Duration.ofSeconds(2)); + } + assertThat(outcome).isEqualTo(Outcome.TERMINAL_FAILURE); + long failedVersion = + hosting + .dsl() + .fetchSingle( + "SELECT row_version FROM subscription_lifecycle_operations WHERE request_id = ?", + failedRequest) + .get(0, Long.class); + long subscriptionVersion = + hosting.intents().findCurrentByTenant(hosting.tenantId()).orElseThrow().rowVersion(); + var input = + new Input( + UUID.randomUUID(), + failedRequest, + hosting.creation().requestId(), + hosting.creation().subscriptionId(), + hosting.tenantId(), + failedVersion, + subscriptionVersion, + UUID.randomUUID(), + "Same-owner recovery from independently observed terminal cancellation"); + hosting.providerStatus("canceled"); + var failed = new FailedHosting(issued, hosting, input, null); + return new FailedHosting(issued, hosting, input, failureImage(failed)); + } + + private static AccountHostingSubscriptionTerminalResolutionService service(FailedHosting failed) { + return new AccountHostingSubscriptionTerminalResolutionService( + failed.issued().actors(), + failed.issued().sources().primary, + failed.hosting().lifecycleRepository(), + failed.hosting().observer(), + failed.hosting().clock()); + } + + private static TransitionResult resolve(FailedHosting failed, String email, String secret) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return service(failed).resolve(failed.issued().compact(), email, secret, failed.input()); + } + + private static void assertCommittedCancellation(FailedHosting failed, TransitionResult result) { + var hosting = failed.hosting(); + var input = failed.input(); + assertThat(result.outcome()).isEqualTo(Outcome.COMMITTED); + assertThat(result.committedRowVersion()).isEqualTo(input.expectedSubscriptionVersion() + 2); + var actor = failed.issued().actors().authenticateAccount(failed.issued().compact()); + var journal = + hosting + .dsl() + .fetchSingle( + "SELECT *, xmin::text AS row_xmin FROM subscription_lifecycle_terminal_resolutions " + + "WHERE resolution_request_id = ?", + input.resolutionRequestId()); + assertThat(journal.get("actor_account_id", UUID.class)).isEqualTo(actor.accountId()); + assertThat(journal.get("control_ui_issuance_operation_id", UUID.class)) + .isEqualTo(actor.issuanceOperationId()); + assertThat(journal.get("control_ui_token_hash", String.class)).isEqualTo(actor.tokenHash()); + assertThat(journal.get("authorization_outcome", String.class)) + .isEqualTo("PRIMARY_AUTHENTICATED"); + assertThat(journal.get("state", String.class)).isEqualTo("COMMITTED"); + assertThat(journal.get("authenticated_at", OffsetDateTime.class).toInstant()) + .isEqualTo(hosting.clock().instant()); + var receipt = + hosting + .dsl() + .fetchSingle( + "SELECT *, xmin::text AS row_xmin FROM subscription_lifecycle_receipts WHERE request_id = ?", + input.resolutionRequestId()); + assertThat(receipt.get("status", String.class)).isEqualTo("canceled"); + assertThat(receipt.get("receipt_digest", String.class)) + .isEqualTo(journal.get("receipt_digest")); + assertThat(receipt.get("subscription_row_version", Long.class)) + .isEqualTo(result.committedRowVersion()); + assertThat(receipt.get("committed_transaction_id", Long.class)) + .isEqualTo(journal.get("created_transaction_id", Long.class)); + var subscription = + hosting + .dsl() + .fetchSingle( + "SELECT *, xmin::text AS row_xmin FROM subscription WHERE subscription_id = ?", + input.subscriptionId()); + assertThat(subscription.get("status", String.class)).isEqualTo("canceled"); + assertThat(subscription.get("lifecycle_inflight_request_id", UUID.class)).isNull(); + assertThat(subscription.get("current_receipt_request_id", UUID.class)) + .isEqualTo(input.resolutionRequestId()); + assertThat(subscription.get("row_version", Long.class)).isEqualTo(result.committedRowVersion()); + var reservation = + hosting + .dsl() + .fetchSingle( + "SELECT *, xmin::text AS row_xmin FROM subscription_instrument_reservations WHERE request_id = ?", + input.creationRequestId()); + assertThat(reservation.get("released_at")).isNotNull(); + assertThat(reservation.get("terminal_resolution_id", UUID.class)) + .isEqualTo(subscription.get("terminal_resolution_id", UUID.class)); + var terminal = + hosting + .dsl() + .fetchSingle( + "SELECT *, xmin::text AS row_xmin FROM subscription_provider_terminal_resolutions WHERE resolution_id = ?", + subscription.get("terminal_resolution_id", UUID.class)); + assertThat(terminal.get("outcome", String.class)).isEqualTo("CANCELED"); + assertThat(terminal.get("provider_subscription_id", String.class)) + .isEqualTo(hosting.providerId()); + var audit = + hosting + .dsl() + .fetchSingle( + "SELECT *, xmin::text AS row_xmin FROM account_audit_outbox WHERE audit_event_id = ?", + input.auditEventId()); + assertThat(audit.get("event_type", String.class)) + .isEqualTo("HOSTING_SUBSCRIPTION_TERMINAL_RESOLVED"); + assertThat(audit.get("payload_digest", String.class)).isEqualTo(journal.get("request_digest")); + var billing = + hosting + .dsl() + .fetchSingle( + "SELECT *, xmin::text AS row_xmin FROM account_tenant_entitlement_outbox_events " + + "WHERE tenant_uuid = ? AND request_id = ?", + hosting.tenantId(), + input.resolutionRequestId()); + assertThat(billing.get("event_id", UUID.class)) + .isEqualTo(receipt.get("billing_event_id", UUID.class)); + assertThat(billing.get("event_digest", String.class)) + .isEqualTo(receipt.get("billing_event_digest")); + var authority = + hosting + .dsl() + .fetchSingle( + "SELECT *, xmin::text AS row_xmin FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence = ?", + TenantAuthorityEventV1Codec.streamKey(hosting.tenantId()), + receipt.get("authority_sequence", Long.class)); + var event = TenantAuthorityEventV1Codec.verify(authority.get("payload", byte[].class)); + assertThat(event.eventDigest()).isEqualTo(receipt.get("authority_event_digest", String.class)); + assertThat(event.tenantBillingSequence()) + .isEqualTo(receipt.get("billing_sequence", Long.class)); + for (var row : + List.of(receipt, subscription, reservation, terminal, audit, billing, authority)) { + assertThat(row.get("row_xmin", String.class)) + .isEqualTo(journal.get("row_xmin", String.class)); + } + assertThat(count(hosting, "subscription_lifecycle_terminal_resolutions")).isOne(); + assertThat(count(hosting, "subscription_lifecycle_receipts")).isOne(); + assertThat(count(hosting, "subscription_provider_terminal_resolutions")).isOne(); + } + + private static long count(Fixture hosting, String table) { + return hosting.dsl().fetchSingle("SELECT count(*) FROM " + table).get(0, Long.class); + } + + private static String failureImage(FailedHosting failed) { + return failed + .hosting() + .dsl() + .fetchSingle( + "SELECT to_jsonb(operation)::text || operation.xmin::text || to_jsonb(notice)::text || notice.xmin::text " + + "FROM subscription_lifecycle_operations operation JOIN subscription_lifecycle_operator_outbox notice " + + "USING (request_id) WHERE request_id = ?", + failed.input().failedRequestId()) + .get(0, String.class); + } + + private static Map financialImage(FailedHosting failed) { + Map image = new LinkedHashMap<>(); + DSLContext dsl = failed.hosting().dsl(); + for (String table : + List.of( + "subscription", + "subscription_current_observations", + "subscription_provisioning_work", + "subscription_lifecycle_operations", + "subscription_lifecycle_attempts", + "subscription_lifecycle_observations", + "subscription_lifecycle_receipts", + "subscription_lifecycle_terminal_resolutions", + "subscription_lifecycle_operator_outbox", + "subscription_provider_history", + "subscription_provider_terminal_resolutions", + "subscription_instrument_reservations", + "account_audit_outbox", + "account_tenant_entitlement_outbox_events", + "account_tenant_entitlement_outbox_streams", + "account_tenant_authority_source_records")) { + image.put(table, rows(dsl, table, "")); + } + image.put( + "tenant_generations", + rows(dsl, "account_authority_generations", " WHERE scope_kind = 'TENANT'")); + String stream = TenantAuthorityEventV1Codec.streamKey(failed.hosting().tenantId()); + for (String table : + List.of("account_authority_outbox_events", "account_authority_outbox_streams")) { + image.put( + table, + dsl.fetchSingle( + "SELECT coalesce(jsonb_agg(snapshot ORDER BY snapshot::text)::text, '[]') FROM " + + "(SELECT to_jsonb(value) || jsonb_build_object('xmin',value.xmin::text) AS snapshot FROM " + + table + + " value WHERE outbox_stream_key = ?) retained", + stream) + .get(0, String.class)); + } + return image; + } + + private static String rows(DSLContext dsl, String table, String where) { + return dsl.fetchSingle( + "SELECT coalesce(jsonb_agg(snapshot ORDER BY snapshot::text)::text, '[]') FROM " + + "(SELECT to_jsonb(value) || jsonb_build_object('xmin',value.xmin::text) AS snapshot FROM " + + table + + " value" + + where + + ") retained") + .get(0, String.class); + } + + private record FailedHosting( + IssuedAccount issued, Fixture hosting, Input input, String failureImage) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java new file mode 100644 index 0000000000..17e160a886 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java @@ -0,0 +1,478 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.stripe.exception.StripeException; +import com.stripe.model.StripeObject; +import com.stripe.net.ApiMode; +import com.stripe.net.ApiResource.RequestMethod; +import com.stripe.net.BaseAddress; +import com.stripe.net.RequestOptions; +import com.stripe.net.StripeResponseGetter; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountHostingPlanQuote; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreationRecord; +import org.junit.jupiter.api.Test; + +/** Real SDK transport proof with explicitly controlled private owner-dispatch inputs. */ +class StripeHostingSubscriptionProvisionerTest { + private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); + private static final UUID ACCOUNT = UUID.randomUUID(); + private static final UUID CUSTOMER_OPERATION = UUID.randomUUID(); + private static final UUID CUSTOMER_KEY = UUID.randomUUID(); + private static final UUID OPERATION = UUID.randomUUID(); + private static final UUID SUBSCRIPTION = UUID.randomUUID(); + private static final AccountSubscriptionCreationRecord CREATION = + new AccountSubscriptionCreationRecord( + UUID.randomUUID(), + "sha256:" + "a".repeat(64), + SUBSCRIPTION, + UUID.randomUUID(), + new OwnerFence(ACCOUNT, 1, UUID.randomUUID()), + "hosting", + new AccountHostingPlanQuote("hosting", "price_exact", 2, 10, 1, 100), + UUID.randomUUID(), + 1, + CUSTOMER_OPERATION, + "cus_exact", + OPERATION, + UUID.randomUUID(), + "pending", + 1, + NOW.minusSeconds(1)); + + @Test + void initialCreateUsesExactDurableBindingsAndKeyThenIndependentlyReadsProvider() { + Transport transport = transport(search(""), subscription(), subscription()); + var located = + (StripeHostingSubscriptionProvisioner.Located) adapter(transport).provision(dispatch(true)); + assertThat(located.providerSubscriptionId()).isEqualTo("sub_exact"); + assertThat(located.observation().providerQuantity()).isEqualTo(2); + assertThat(transport.paths) + .containsExactly( + "/v1/customers/cus_exact", + "/v1/payment_methods/pm_exact", + "/v1/subscriptions/search", + "/v1/subscriptions", + "/v1/subscriptions/sub_exact"); + assertThat(transport.methods) + .containsExactly( + RequestMethod.GET, + RequestMethod.GET, + RequestMethod.GET, + RequestMethod.POST, + RequestMethod.GET); + assertThat(transport.options) + .extracting(RequestOptions::getIdempotencyKey) + .containsExactly(null, null, null, OPERATION.toString(), null); + assertThat(transport.options) + .allSatisfy( + options -> { + assertThat(options.getConnectTimeout()).isEqualTo(250); + assertThat(options.getReadTimeout()).isEqualTo(1000); + assertThat(options.getMaxNetworkRetries()).isZero(); + }); + assertThat(transport.params.get(3)) + .containsOnlyKeys( + "customer", + "default_payment_method", + "items", + "metadata", + "collection_method", + "payment_behavior"); + assertThat(transport.params.get(3)) + .containsEntry("customer", "cus_exact") + .containsEntry("default_payment_method", "pm_exact") + .containsEntry("collection_method", "charge_automatically") + .containsEntry("payment_behavior", "default_incomplete"); + assertThat(StripeHostingSubscriptionProvisioner.Located.class.getConstructors()).isEmpty(); + } + + @Test + void unknownOrExpiredIdempotencyOutcomeNeverAuthorizesAnotherCreate() { + Transport missing = transport(search(""), subscriptionList()); + assertThat(adapter(missing).provision(dispatch(false))) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending("PROVIDER_LOOKUP_UNRESOLVED", null)); + assertThat(missing.paths) + .containsExactly( + "/v1/customers/cus_exact", + "/v1/payment_methods/pm_exact", + "/v1/subscriptions/search", + "/v1/subscriptions"); + assertThat(missing.methods) + .containsExactly( + RequestMethod.GET, RequestMethod.GET, RequestMethod.GET, RequestMethod.GET); + assertThat(missing.params.get(3)) + .containsEntry("customer", "cus_exact") + .containsEntry("status", "all") + .containsEntry("limit", 100L); + Transport lost = transport(search(""), subscription()); + lost.failureAt = 3; + lost.failure = mock(StripeException.class); + assertThat(adapter(lost).provision(dispatch(true))) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending( + "PROVIDER_OUTCOME_UNKNOWN", lost.failure)); + assertThat(lost.paths) + .containsExactly( + "/v1/customers/cus_exact", + "/v1/payment_methods/pm_exact", + "/v1/subscriptions/search", + "/v1/subscriptions"); + assertThat(lost.methods) + .containsExactly( + RequestMethod.GET, RequestMethod.GET, RequestMethod.GET, RequestMethod.POST); + Transport recovered = transport(search(subscription()), subscription()); + assertThat(adapter(recovered).provision(dispatch(false))) + .isInstanceOf(StripeHostingSubscriptionProvisioner.Located.class); + assertThat(recovered.paths) + .containsExactly( + "/v1/customers/cus_exact", + "/v1/payment_methods/pm_exact", + "/v1/subscriptions/search", + "/v1/subscriptions/sub_exact"); + assertThat(recovered.methods) + .containsExactly( + RequestMethod.GET, RequestMethod.GET, RequestMethod.GET, RequestMethod.GET); + } + + @Test + void emptySearchUsesBoundedCustomerListOnlyForNonInitialLookup() { + Transport recovered = transport(search(""), subscriptionList(subscription()), subscription()); + var located = + (StripeHostingSubscriptionProvisioner.Located) + adapter(recovered).provision(dispatch(false)); + assertThat(located.providerSubscriptionId()).isEqualTo("sub_exact"); + assertThat(recovered.paths) + .containsExactly( + "/v1/customers/cus_exact", + "/v1/payment_methods/pm_exact", + "/v1/subscriptions/search", + "/v1/subscriptions", + "/v1/subscriptions/sub_exact"); + assertThat(recovered.methods) + .containsExactly( + RequestMethod.GET, + RequestMethod.GET, + RequestMethod.GET, + RequestMethod.GET, + RequestMethod.GET); + assertThat(recovered.params.get(3)) + .containsEntry("customer", "cus_exact") + .containsEntry("status", "all") + .containsEntry("limit", 100L); + + Transport incomplete = transport(search(""), subscriptionList(true, subscription())); + assertThat(adapter(incomplete).provision(dispatch(false))) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending( + "INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null)); + assertThat(incomplete.paths) + .containsExactly( + "/v1/customers/cus_exact", + "/v1/payment_methods/pm_exact", + "/v1/subscriptions/search", + "/v1/subscriptions"); + + Transport ambiguous = + transport(search(""), subscriptionList(subscription() + "," + subscription())); + assertThat(adapter(ambiguous).provision(dispatch(false))) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending( + "INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null)); + assertThat(ambiguous.paths) + .containsExactly( + "/v1/customers/cus_exact", + "/v1/payment_methods/pm_exact", + "/v1/subscriptions/search", + "/v1/subscriptions"); + + Transport wrongCustomer = + transport(search(""), subscriptionList(subscription().replace("cus_exact", "cus_other"))); + assertThat(adapter(wrongCustomer).provision(dispatch(false))) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending( + "INCOMPLETE_OR_AMBIGUOUS_PROVIDER_LIST", null)); + Transport wrongMetadata = + transport( + search(""), + subscriptionList( + subscription().replace(OPERATION.toString(), UUID.randomUUID().toString()))); + assertThat(adapter(wrongMetadata).provision(dispatch(false))) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending("PROVIDER_LOOKUP_UNRESOLVED", null)); + } + + @Test + void searchFailureDuplicatesAndIndependentBindingMismatchRemainNonterminal() { + Transport failed = transport(search("")); + failed.failureAt = 2; + failed.failure = mock(StripeException.class); + assertThat(adapter(failed).provision(dispatch(true))) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending( + "PROVIDER_OUTCOME_UNKNOWN", failed.failure)); + assertThat(failed.paths) + .containsExactly( + "/v1/customers/cus_exact", "/v1/payment_methods/pm_exact", "/v1/subscriptions/search"); + assertThat(failed.methods) + .containsExactly(RequestMethod.GET, RequestMethod.GET, RequestMethod.GET); + Transport duplicate = transport(search(subscription() + "," + subscription())); + assertThat(adapter(duplicate).provision(dispatch(true))) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending( + "INCOMPLETE_OR_AMBIGUOUS_PROVIDER_SEARCH", null)); + assertThat(duplicate.paths) + .containsExactly( + "/v1/customers/cus_exact", "/v1/payment_methods/pm_exact", "/v1/subscriptions/search"); + assertThat(duplicate.methods) + .containsExactly(RequestMethod.GET, RequestMethod.GET, RequestMethod.GET); + Transport mismatch = + transport(search(subscription()), subscription().replace("pm_exact", "pm_wrong")); + assertThat(adapter(mismatch).provision(dispatch(false))) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending( + "INDEPENDENT_PROVIDER_READBACK_UNRESOLVED", null)); + assertThat(mismatch.paths) + .containsExactly( + "/v1/customers/cus_exact", + "/v1/payment_methods/pm_exact", + "/v1/subscriptions/search", + "/v1/subscriptions/sub_exact"); + assertThat(mismatch.methods) + .containsExactly( + RequestMethod.GET, RequestMethod.GET, RequestMethod.GET, RequestMethod.GET); + } + + @Test + void incompleteFirstInvoiceRemainsNonAuthorizingWithoutAnyPaymentConfirmationCall() { + String incomplete = + subscription().replace("\"status\":\"active\"", "\"status\":\"incomplete\""); + Transport transport = transport(search(""), incomplete, incomplete); + var located = + (StripeHostingSubscriptionProvisioner.Located) adapter(transport).provision(dispatch(true)); + assertThat(located.observation().providerStatus()).isEqualTo("incomplete"); + var policy = + new AccountHostingSubscriptionLifecyclePolicy( + Duration.ofSeconds(30), + new RecoveryTiming(Duration.ofMinutes(1), Duration.ofMinutes(1))); + var decision = policy.evaluate(located.observation(), NOW, null); + assertThat(decision.resolved()).isFalse(); + assertThat(decision.reason()) + .isEqualTo(AccountHostingSubscriptionLifecyclePolicy.Reason.UNMAPPED_PROVIDER_STATUS); + assertThat(transport.params.get(3)).containsEntry("payment_behavior", "default_incomplete"); + assertThat(transport.paths) + .containsExactly( + "/v1/customers/cus_exact", + "/v1/payment_methods/pm_exact", + "/v1/subscriptions/search", + "/v1/subscriptions", + "/v1/subscriptions/sub_exact"); + assertThat(transport.methods) + .containsExactly( + RequestMethod.GET, + RequestMethod.GET, + RequestMethod.GET, + RequestMethod.POST, + RequestMethod.GET); + } + + @Test + void uncommittedDispatchAndExpiredLeaseRefuseBeforeSdkIo() { + Transport transport = new Transport(); + ProviderDispatch uncommitted = dispatch(true); + when(uncommitted.readyForProviderIo()).thenReturn(false); + assertThatThrownBy(() -> adapter(transport).provision(uncommitted)) + .hasMessageContaining("independent"); + var expired = + new StripeHostingSubscriptionProvisioner( + new com.stripe.StripeClient(transport), + Clock.fixed(NOW.plusSeconds(20), ZoneOffset.UTC), + false, + Duration.ofMillis(250), + Duration.ofSeconds(1)); + assertThat(expired.provision(dispatch(true))) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending("DISPATCH_LEASE_EXPIRED", null)); + assertThat(transport.paths).isEmpty(); + assertThat(transport.methods).isEmpty(); + } + + @Test + void mismatchedProviderInstrumentAndAmbientTransactionCannotReachCreate() { + Transport detached = transport(search("")); + // The controlled PaymentMethod now names another Customer: no search/create follows. + var responses = new ArrayList<>(detached.responses); + responses.set(1, responses.get(1).replace("cus_exact", "cus_other")); + Transport mismatch = new Transport(responses.toArray(String[]::new)); + assertThat(adapter(mismatch).provision(dispatch(true))) + .isEqualTo( + new StripeHostingSubscriptionProvisioner.Pending( + "PROVIDER_PREREQUISITES_UNRESOLVED", null)); + assertThat(mismatch.paths) + .containsExactly("/v1/customers/cus_exact", "/v1/payment_methods/pm_exact"); + assertThat(mismatch.methods).containsExactly(RequestMethod.GET, RequestMethod.GET); + Transport ambient = new Transport(); + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(true); + try { + assertThatThrownBy(() -> adapter(ambient).provision(dispatch(true))) + .hasMessageContaining("ambient SQL"); + assertThat(ambient.paths).isEmpty(); + assertThat(ambient.methods).isEmpty(); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(false); + } + } + + private static ProviderDispatch dispatch(boolean initial) { + var claim = mock(ProvisioningClaim.class); + when(claim.creation()).thenReturn(CREATION); + when(claim.claimedAt()).thenReturn(NOW.minusSeconds(1)); + when(claim.expiresAt()).thenReturn(NOW.plusSeconds(10)); + var dispatch = mock(ProviderDispatch.class); + when(dispatch.claim()).thenReturn(claim); + when(dispatch.providerPaymentMethodId()).thenReturn("pm_exact"); + when(dispatch.customerProviderIdempotencyId()).thenReturn(CUSTOMER_KEY); + when(dispatch.readyForProviderIo()).thenReturn(true); + when(dispatch.initialCallAllowed()).thenReturn(initial); + when(dispatch.expectedBinding("sub_exact")) + .thenReturn( + new StripeHostingSubscriptionObserver.ExpectedBinding( + "sub_exact", + SUBSCRIPTION, + "cus_exact", + "pm_exact", + "price_exact", + 2, + StripeHostingSubscriptionObserver.OperationType.SUBSCRIPTION_PROVISIONING, + OPERATION, + false)); + return dispatch; + } + + private static StripeHostingSubscriptionProvisioner adapter(Transport transport) { + return new StripeHostingSubscriptionProvisioner( + new com.stripe.StripeClient(transport), + Clock.fixed(NOW, ZoneOffset.UTC), + false, + Duration.ofMillis(250), + Duration.ofSeconds(1)); + } + + private static Transport transport(String... responses) { + var all = new ArrayList(); + all.add( + "{\"object\":\"customer\",\"id\":\"cus_exact\",\"livemode\":false,\"deleted\":false,\"metadata\":{" + + "\"firemud_metadata_schema_version\":\"1\",\"firemud_operation_type\":\"customer_provisioning\"," + + "\"firemud_operation_id\":\"" + + CUSTOMER_OPERATION + + "\",\"firemud_account_id\":\"" + + ACCOUNT + + "\"}}"); + all.add( + "{\"object\":\"payment_method\",\"id\":\"pm_exact\",\"customer\":\"cus_exact\",\"livemode\":false," + + "\"type\":\"card\",\"card\":{\"brand\":\"visa\",\"last4\":\"4242\",\"exp_month\":12,\"exp_year\":2030}}"); + all.addAll(List.of(responses)); + return new Transport(all.toArray(String[]::new)); + } + + private static String search(String objects) { + return "{\"object\":\"search_result\",\"has_more\":false,\"data\":[" + objects + "]}"; + } + + private static String subscriptionList(String... objects) { + return subscriptionList(false, objects); + } + + private static String subscriptionList(boolean hasMore, String... objects) { + return "{\"object\":\"list\",\"has_more\":" + + hasMore + + ",\"data\":[" + + String.join(",", objects) + + "]}"; + } + + private static String subscription() { + return "{\"object\":\"subscription\",\"id\":\"sub_exact\",\"customer\":\"cus_exact\",\"default_payment_method\":\"pm_exact\"," + + "\"livemode\":false,\"status\":\"active\",\"cancel_at_period_end\":false,\"metadata\":{" + + "\"firemud_metadata_schema_version\":\"1\",\"firemud_operation_type\":\"subscription_provisioning\"," + + "\"firemud_operation_id\":\"" + + OPERATION + + "\",\"firemud_subscription_id\":\"" + + SUBSCRIPTION + + "\"}," + + "\"items\":{\"has_more\":false,\"data\":[{\"id\":\"si_exact\",\"object\":\"subscription_item\",\"subscription\":\"sub_exact\"," + + "\"quantity\":2,\"current_period_start\":1793577500,\"current_period_end\":1793578500,\"price\":{\"id\":\"price_exact\",\"object\":\"price\"}}]}}"; + } + + private static final class Transport implements StripeResponseGetter { + private final List responses; + private final List paths = new ArrayList<>(); + private final List methods = new ArrayList<>(); + private final List> params = new ArrayList<>(); + private final List options = new ArrayList<>(); + private int failureAt = -1; + private StripeException failure; + + private Transport(String... responses) { + this.responses = List.of(responses); + } + + @Override + @SuppressWarnings("unchecked") + public T request( + BaseAddress base, + RequestMethod method, + String path, + Map parameters, + Type type, + RequestOptions requestOptions, + ApiMode mode) + throws StripeException { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + int index = paths.size(); + paths.add(path); + methods.add(method); + params.add(parameters == null ? Map.of() : Map.copyOf(parameters)); + options.add(requestOptions); + if (index == failureAt) { + throw failure; + } + return (T) com.stripe.net.ApiResource.GSON.fromJson(responses.get(index), type); + } + + @Override + public InputStream requestStream( + BaseAddress base, + RequestMethod method, + String path, + Map parameters, + RequestOptions options, + ApiMode mode) { + throw new AssertionError("No streaming"); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java index 19b9f00349..d201170637 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java @@ -72,6 +72,7 @@ void expiredExactAttemptBeforeAbsoluteDeadlineLeavesWorkAndReservationUntouched( long secondsAfterExpiry) { Instant expiresAt = Instant.parse("2026-11-07T00:00:10Z"); UUID requestId = UUID.randomUUID(); + UUID subscriptionId = UUID.randomUUID(); UUID attemptId = UUID.randomUUID(); var controlledIntents = mock(AccountSubscriptionIntentRepository.class); var controlledRepository = @@ -88,20 +89,47 @@ void expiredExactAttemptBeforeAbsoluteDeadlineLeavesWorkAndReservationUntouched( false); var creation = mock(AccountSubscriptionCreationRecord.class); when(creation.requestId()).thenReturn(requestId); + when(creation.subscriptionId()).thenReturn(subscriptionId); + when(controlledIntents.findCreation(requestId)).thenReturn(Optional.of(creation)); + var current = mock(AccountSubscriptionCurrentRecord.class); + when(current.subscriptionId()).thenReturn(subscriptionId); + when(current.rowVersion()).thenReturn(7L); + when(controlledIntents.lockForProvisioningSettlement(requestId, 7L)).thenReturn(current); var claim = mock(ProvisioningClaim.class); when(claim.creation()).thenReturn(creation); when(claim.attemptId()).thenReturn(attemptId); + when(claim.attemptNumber()).thenReturn(2); when(claim.subscriptionRowVersion()).thenReturn(7L); when(claim.claimedAt()).thenReturn(expiresAt.minusSeconds(10)); when(claim.expiresAt()).thenReturn(expiresAt); var retainedWork = mock(Record.class); when(retainedWork.get("last_attempt_id", UUID.class)).thenReturn(attemptId); + when(retainedWork.get("last_attempt_id")).thenReturn(attemptId); + when(retainedWork.get("subscription_id", UUID.class)).thenReturn(subscriptionId); + when(retainedWork.get("subscription_row_version", Long.class)).thenReturn(7L); when(retainedWork.get("phase", String.class)).thenReturn("CLAIMED"); when(retainedWork.get("deadline_at", OffsetDateTime.class)) .thenReturn(expiresAt.plusSeconds(3590).atOffset(ZoneOffset.UTC)); String lockedWorkSql = "SELECT * FROM subscription_provisioning_work WHERE request_id = ? FOR UPDATE"; when(dsl.fetchOne(lockedWorkSql, requestId)).thenReturn(retainedWork); + String linksSql = + "SELECT lifecycle_inflight_request_id, current_receipt_request_id " + + "FROM subscription WHERE subscription_id = ?"; + var links = mock(Record.class); + when(dsl.fetchOne(linksSql, subscriptionId)).thenReturn(links); + String retainedAttemptSql = + "SELECT * FROM subscription_provisioning_attempts WHERE attempt_id = ?"; + var retainedAttempt = mock(Record.class); + when(retainedAttempt.get("request_id", UUID.class)).thenReturn(requestId); + when(retainedAttempt.get("subscription_id", UUID.class)).thenReturn(subscriptionId); + when(retainedAttempt.get("attempt_number", Integer.class)).thenReturn(2); + when(retainedAttempt.get("claimed_row_version", Long.class)).thenReturn(7L); + when(retainedAttempt.get("claimed_at", OffsetDateTime.class)) + .thenReturn(expiresAt.minusSeconds(10).atOffset(ZoneOffset.UTC)); + when(retainedAttempt.get("expires_at", OffsetDateTime.class)) + .thenReturn(expiresAt.atOffset(ZoneOffset.UTC)); + when(dsl.fetchOne(retainedAttemptSql, attemptId)).thenReturn(retainedAttempt); var databaseClock = mock(Record.class); when(databaseClock.get("now", OffsetDateTime.class)) .thenReturn(expiresAt.plusSeconds(secondsAfterExpiry).atOffset(ZoneOffset.UTC)); @@ -110,10 +138,13 @@ void expiredExactAttemptBeforeAbsoluteDeadlineLeavesWorkAndReservationUntouched( assertThat(controlledRepository.deferUnresolved(claim)).isEqualTo(Disposition.ATTEMPT_EXPIRED); - // Only owner/retained-work locks and the database clock are read: no SQL writes, settlement, - // reservation release, or replacement attempt can occur on this return. - verify(controlledIntents).lockForProvisioningRecovery(requestId, 7L); + // Only the exact local owner/work locks, retained attempt, lifecycle ownership and DB clock + // are read: no SQL writes, reservation release, or replacement attempt occur on this return. + verify(controlledIntents).lockForProvisioningSettlement(requestId, 7L); + verify(controlledIntents).findCreation(requestId); verify(dsl).fetchOne(lockedWorkSql, requestId); + verify(dsl).fetchOne(linksSql, subscriptionId); + verify(dsl).fetchOne(retainedAttemptSql, attemptId); verify(dsl).fetchOne("SELECT clock_timestamp() AS now"); verifyNoMoreInteractions(controlledIntents, dsl); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java new file mode 100644 index 0000000000..32590851fa --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java @@ -0,0 +1,199 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionProvisioner; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.Disposition; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProviderDispatch; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ProvisioningClaim; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountHostingSubscriptionProvisioningServiceTest { + private final AccountHostingSubscriptionLifecycleRepository repository = + mock(AccountHostingSubscriptionLifecycleRepository.class); + private final StripeHostingSubscriptionProvisioner provider = + mock(StripeHostingSubscriptionProvisioner.class); + private final AccountHostingSubscriptionLifecycleService lifecycle = + mock(AccountHostingSubscriptionLifecycleService.class); + private final LocalTransactions transactions = new LocalTransactions(); + private final AccountHostingSubscriptionProvisioningService service = + new AccountHostingSubscriptionProvisioningService( + repository, provider, lifecycle, transactions); + private final ProvisioningClaim claim = mock(ProvisioningClaim.class); + + @AfterEach + void clearAmbient() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void claimCommitAndIndependentReadbackPrecedeProviderAndUnknownOutcomeDefersWithoutLifecycle() { + ProviderDispatch prepared = mock(ProviderDispatch.class); + ProviderDispatch readback = mock(ProviderDispatch.class); + when(readback.claim()).thenReturn(claim); + when(repository.prepareProviderDispatch(any(), any())) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return prepared; + }); + when(repository.readProviderDispatch(prepared)) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(transactions.commits).isEqualTo(1); + return readback; + }); + when(provider.provision(readback)) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(transactions.commits).isEqualTo(2); + return new StripeHostingSubscriptionProvisioner.Pending("UNKNOWN", null); + }); + when(repository.deferUnresolved(claim)) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return Disposition.WAITING; + }); + var result = + (AccountHostingSubscriptionProvisioningService.Pending) + service.provision(claim, UUID.randomUUID(), UUID.randomUUID()); + assertThat(result.disposition()).isEqualTo(Disposition.WAITING); + assertThat(transactions.commits).isEqualTo(3); + verifyNoInteractions(lifecycle); + } + + @ParameterizedTest + @ValueSource(strings = {"DISPATCH_LEASE_EXPIRED", "PROVIDER_OUTCOME_UNKNOWN"}) + void expiredAttemptReturnsTypedPendingWithoutStartingLifecycle(String providerReason) { + ProviderDispatch prepared = mock(ProviderDispatch.class); + ProviderDispatch readback = mock(ProviderDispatch.class); + when(readback.claim()).thenReturn(claim); + when(repository.prepareProviderDispatch(any(), any())).thenReturn(prepared); + when(repository.readProviderDispatch(prepared)).thenReturn(readback); + var providerResult = new StripeHostingSubscriptionProvisioner.Pending(providerReason, null); + when(provider.provision(readback)).thenReturn(providerResult); + when(repository.deferUnresolved(claim)) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return Disposition.ATTEMPT_EXPIRED; + }); + + assertThat(service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) + .isEqualTo( + new AccountHostingSubscriptionProvisioningService.Pending( + Disposition.ATTEMPT_EXPIRED, providerResult)); + assertThat(transactions.commits).isEqualTo(3); + verifyNoInteractions(lifecycle); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void refusedDispatchCommitsLocalDeferralWithoutCallingProvider(boolean readbackRefused) { + ProviderDispatch prepared = mock(ProviderDispatch.class); + if (readbackRefused) { + when(repository.prepareProviderDispatch(any(), any())).thenReturn(prepared); + when(repository.readProviderDispatch(prepared)) + .thenThrow(new FenceRejectedException("wallet observation advanced")); + } else { + when(repository.prepareProviderDispatch(any(), any())) + .thenThrow(new FenceRejectedException("wallet observation advanced")); + } + when(repository.deferUnresolved(claim)) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return Disposition.TERMINAL_FAILURE; + }); + + assertThat(service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) + .isEqualTo( + new AccountHostingSubscriptionProvisioningService.Pending( + Disposition.TERMINAL_FAILURE, + new StripeHostingSubscriptionProvisioner.Pending("DISPATCH_FENCE_REJECTED", null))); + assertThat(transactions.commits).isEqualTo(readbackRefused ? 2 : 1); + verify(repository).deferUnresolved(claim); + verifyNoInteractions(provider, lifecycle); + } + + @Test + void refusedDispatchCannotHideStaleClaimSettlementFailure() { + when(repository.prepareProviderDispatch(any(), any())) + .thenThrow(new FenceRejectedException("dispatch refused")); + when(repository.deferUnresolved(claim)) + .thenThrow(new FenceRejectedException("stale retained attempt")); + + assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) + .isInstanceOf(FenceRejectedException.class) + .hasMessage("stale retained attempt"); + assertThat(transactions.commits).isZero(); + verifyNoInteractions(provider, lifecycle); + } + + @Test + void failedIndependentReadbackNeverCallsProvider() { + ProviderDispatch prepared = mock(ProviderDispatch.class); + when(repository.prepareProviderDispatch(any(), any())).thenReturn(prepared); + when(repository.readProviderDispatch(prepared)) + .thenThrow(new IllegalStateException("readback rejected")); + assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) + .hasMessageContaining("readback rejected"); + assertThat(transactions.commits).isEqualTo(1); + verifyNoInteractions(provider, lifecycle); + } + + @Test + void ambientTransactionAndSynchronizationRefuseBeforeAnyEffects() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) + .hasMessageContaining("ambient SQL"); + verifyNoInteractions(repository, provider, lifecycle); + } + + private static final class LocalTransactions extends AbstractPlatformTransactionManager { + private int commits; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) {} + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + } + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index bf39db3a85..359dea0f2b 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -18,8 +18,12 @@ import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; class AccountRuntimeStubServerCompatibilityTest { + private static final String TENANT_ID = "5c03483e-d14c-4dc4-806e-297cdd209612"; + private static final String GAME_INSTANCE_ID = "fceab4e7-2922-4e6f-a4f4-dbaab3e25875"; private static final String REALM_ID = "8a1df0f1-1b57-465e-9c4b-bb34f8153d31"; private static final String NAMESPACE_ID = "2ea958e0-13a2-41d0-9c39-59a96cf31412"; private static final Set NON_RUNTIME_METHODS = @@ -65,6 +69,7 @@ void joinMembershipVersionsRemainUnsignedOnTheirExistingFieldNumbers() { assertField(descriptor, "membership_version", 6, FieldDescriptor.Type.UINT64); assertField(descriptor, "membership_authority_generation", 7, FieldDescriptor.Type.UINT64); + assertField(descriptor, "gameplay_admission_allowed", 10, FieldDescriptor.Type.BOOL); } @Test @@ -98,10 +103,10 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe PlayerExecutionContext caller = PlayerExecutionContext.newBuilder() .setAccountId(accountUuid) - .setTenantId("11") + .setTenantId(TENANT_ID) .setRealmId(REALM_ID) - .setGameInstanceId("33") - .setSessionId("session-1") + .setGameInstanceId(GAME_INSTANCE_ID) + .setSessionId("1") .setPlayableStateNamespaceId(NAMESPACE_ID) .setPlayableStateScope("SHARED") .setRequestId("join-request-1") @@ -110,13 +115,13 @@ void runtimeMembershipLifecycleRemainsSeparateFromAdmissionAndJoinDoesNotGrantRe stub.issueDirectTextConnectScope( IssueDirectTextConnectScopeRequest.newBuilder() .setPlayerContext(caller) - .setTenantId("11") + .setTenantId(TENANT_ID) .setWorldSlug("demo") .setRealmSlug("live") .setRealmId(REALM_ID) .setPlayableStateNamespaceId(NAMESPACE_ID) .setPlayableStateScope("SHARED") - .setGameInstanceId("33") + .setGameInstanceId(GAME_INSTANCE_ID) .setCatalogRevision(1L) .setPointerVersion(1L) .build()); @@ -181,6 +186,18 @@ void directTextConnectScopeRejectsNoncanonicalIdsAndBlankContextRequestId() thro .setPlayerContext( validRequest.getPlayerContext().toBuilder().setRequestId(" ")) .build(), + validRequest.toBuilder() + .setPlayableStateScope("PRIVATE") + .setPlayerContext( + validRequest.getPlayerContext().toBuilder() + .setPlayableStateScope("PRIVATE")) + .build(), + validRequest.toBuilder().setWorldSlug("w".repeat(129)).build(), + validRequest.toBuilder().setRealmSlug("r".repeat(129)).build(), + validRequest.toBuilder() + .setPlayerContext( + validRequest.getPlayerContext().toBuilder().setRequestId("r".repeat(129))) + .build(), validRequest.toBuilder().setCatalogRevision(0L).build(), validRequest.toBuilder().setPointerVersion(-1L).build()); @@ -195,8 +212,148 @@ void directTextConnectScopeRejectsNoncanonicalIdsAndBlankContextRequestId() thro } } + @ParameterizedTest + @ValueSource( + strings = { + "11", "00000000-0000-0000-0000-000000000000", + "5C03483E-D14C-4DC4-806E-297CDD209612", "1-1-1-1-1" + }) + void directTextScopeAndJoinRejectNoncanonicalTargetIds(String invalidId) throws Exception { + try (var server = new AccountRuntimeStubServer(0)) { + server.mapAccountId("demo@example.com", 7L); + String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); + var channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + var request = validConnectScopeRequest(accountUuid); + var caller = request.getPlayerContext(); + var invalidRequests = + List.of( + request.toBuilder() + .setTenantId(invalidId) + .setPlayerContext(caller.toBuilder().setTenantId(invalidId)) + .build(), + request.toBuilder() + .setRealmId(invalidId) + .setPlayerContext(caller.toBuilder().setRealmId(invalidId)) + .build(), + request.toBuilder() + .setGameInstanceId(invalidId) + .setPlayerContext(caller.toBuilder().setGameInstanceId(invalidId)) + .build(), + request.toBuilder() + .setPlayableStateNamespaceId(invalidId) + .setPlayerContext(caller.toBuilder().setPlayableStateNamespaceId(invalidId)) + .build()); + var join = + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(caller) + .setConnectScopeId(stub.issueDirectTextConnectScope(request).getConnectScopeId()) + .setRequestId(caller.getRequestId()) + .build(); + assertThat(stub.joinPublicProductionMembership(join).getSuccess()).isTrue(); + for (var invalidRequest : invalidRequests) { + var scope = stub.issueDirectTextConnectScope(invalidRequest); + assertThat(scope.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(scope.getConnectScopeId()).isEmpty(); + var replay = + stub.joinPublicProductionMembership( + join.toBuilder().setPlayerContext(invalidRequest.getPlayerContext()).build()); + assertThat(replay.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(replay.getSuccess()).isFalse(); + assertThat(replay.getReplayed()).isFalse(); + } + } finally { + channel.shutdownNow(); + } + } + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + " ", + "session-1", + "0", + "-1", + "+1", + "1.0", + "9223372036854775808", + "00000000000000000000000000000000100" + }) + void directTextScopeAndJoinRejectInvalidTransportSessionsBeforeReplay(String session) + throws Exception { + try (var server = new AccountRuntimeStubServer(0)) { + server.mapAccountId("demo@example.com", 7L); + var channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + var request = + validConnectScopeRequest(AccountRuntimeStubServer.accountUuidForTestFixture(7L)); + var invalidCaller = request.getPlayerContext().toBuilder().setSessionId(session).build(); + var invalidScope = + stub.issueDirectTextConnectScope( + request.toBuilder().setPlayerContext(invalidCaller).build()); + assertThat(invalidScope.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(invalidScope.getConnectScopeId()).isEmpty(); + var join = + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(request.getPlayerContext()) + .setConnectScopeId(stub.issueDirectTextConnectScope(request).getConnectScopeId()) + .setRequestId(request.getPlayerContext().getRequestId()) + .build(); + var invalidJoin = join.toBuilder().setPlayerContext(invalidCaller).build(); + assertThat(stub.joinPublicProductionMembership(invalidJoin).getError().getCode()) + .isEqualTo("INVALID_ARGUMENT"); + assertThat(stub.joinPublicProductionMembership(join).getSuccess()).isTrue(); + var replay = stub.joinPublicProductionMembership(invalidJoin); + assertThat(replay.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(replay.getSuccess()).isFalse(); + assertThat(replay.getReplayed()).isFalse(); + } finally { + channel.shutdownNow(); + } + } + } + + @ParameterizedTest + @ValueSource(strings = {"1", "0001", "9223372036854775807", "00000000000000000000000000000001"}) + void directTextScopeAndJoinAcceptAccountTransportSessionRange(String session) throws Exception { + try (var server = new AccountRuntimeStubServer(0)) { + server.mapAccountId("demo@example.com", 7L); + var channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + var request = + validConnectScopeRequest(AccountRuntimeStubServer.accountUuidForTestFixture(7L)); + request = + request.toBuilder() + .setPlayerContext(request.getPlayerContext().toBuilder().setSessionId(session)) + .build(); + var scope = stub.issueDirectTextConnectScope(request); + assertThat(scope.getError().getCode()).isEmpty(); + var join = + stub.joinPublicProductionMembership( + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(request.getPlayerContext()) + .setConnectScopeId(scope.getConnectScopeId()) + .setRequestId(request.getPlayerContext().getRequestId()) + .build()); + assertThat(join.getSuccess()).isTrue(); + assertThat(join.getTenantId()).isEqualTo(TENANT_ID); + } finally { + channel.shutdownNow(); + } + } + } + @Test - void joinRequiresCallerSessionAndResetClearsRetainedScopes() throws Exception { + void joinRequiresCallerSessionBeforeReplayAndResetClearsRetainedScopesAndOutcomes() + throws Exception { try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { server.mapAccountId("demo@example.com", 7L); String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); @@ -214,20 +371,44 @@ void joinRequiresCallerSessionAndResetClearsRetainedScopes() throws Exception { .setRequestId("join-request-1") .build(); - var blankSession = - stub.joinPublicProductionMembership( - validJoin.toBuilder() - .setPlayerContext(validJoin.getPlayerContext().toBuilder().setSessionId(" ")) - .build()); + var blankSessionRequest = + validJoin.toBuilder() + .setPlayerContext(validJoin.getPlayerContext().toBuilder().setSessionId(" ")) + .build(); + var blankSession = stub.joinPublicProductionMembership(blankSessionRequest); assertThat(blankSession.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); assertThat(blankSession.getSuccess()).isFalse(); assertThat(stub.joinPublicProductionMembership(validJoin).getSuccess()).isTrue(); + for (var invalidRequest : + List.of( + blankSessionRequest, + validJoin.toBuilder().setConnectScopeId("missing-scope").build(), + validJoin.toBuilder() + .setPlayerContext( + validJoin.getPlayerContext().toBuilder() + .setRealmId("a87e157e-d63b-4bac-ad7c-2bd51c7ad81c")) + .build())) { + var invalidReplay = stub.joinPublicProductionMembership(invalidRequest); + assertThat(invalidReplay.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(invalidReplay.getSuccess()).isFalse(); + assertThat(invalidReplay.getReplayed()).isFalse(); + } server.resetRuntimeState(); var afterReset = stub.joinPublicProductionMembership(validJoin); assertThat(afterReset.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); assertThat(afterReset.getSuccess()).isFalse(); + + String freshScopeId = stub.issueDirectTextConnectScope(scopeRequest).getConnectScopeId(); + assertThat(freshScopeId).isNotEqualTo(connectScopeId); + var freshJoin = + stub.joinPublicProductionMembership( + validJoin.toBuilder().setConnectScopeId(freshScopeId).build()); + assertThat(freshJoin.getError().getCode()).isEmpty(); + assertThat(freshJoin.getSuccess()).isTrue(); + assertThat(freshJoin.getOutcomeCode()).isEqualTo("ALREADY_ACTIVE"); + assertThat(freshJoin.getReplayed()).isFalse(); } finally { channel.shutdownNow(); } @@ -308,32 +489,227 @@ void directTextScopeIssuanceAndJoinRequireRegisteredAccountUuidAndKeepClockSnaps } } + @ParameterizedTest + @ValueSource(strings = {"MISSING", "INACTIVE"}) + void joinRetainsTerminalOutcomesAndNewRequestObservesActiveMembership(String lifecycle) + throws Exception { + var clock = Clock.fixed(Instant.parse("2026-10-30T12:34:56Z"), ZoneOffset.UTC); + try (var server = new AccountRuntimeStubServer(0, clock)) { + server.mapAccountId("demo@example.com", 7L); + long previousVersion = "MISSING".equals(lifecycle) ? 1L : 3L; + if ("MISSING".equals(lifecycle)) server.setMembershipExists(false); + else server.setMembershipInactive(); + server.setMembershipVersion(previousVersion); + server.setAllowPublicJoin(false); + String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); + var scopeRequest = validConnectScopeRequest(accountUuid); + var channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + var scope = stub.issueDirectTextConnectScope(scopeRequest); + var request = + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(scopeRequest.getPlayerContext()) + .setConnectScopeId(scope.getConnectScopeId()) + .setRequestId("join-request-1") + .build(); + var before = stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); + var denied = stub.joinPublicProductionMembership(request); + assertThat(denied.getSuccess()).isFalse(); + assertThat(denied.getOutcomeCode()).isEqualTo("PUBLIC_PRODUCTION_ADMISSION_DENIED"); + assertThat(denied.getReplayed()).isFalse(); + assertThat(stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11"))) + .isEqualTo(before); + + server.setAllowPublicJoin(true); + var deniedReplay = stub.joinPublicProductionMembership(request); + assertThat(deniedReplay).isEqualTo(denied.toBuilder().setReplayed(true).build()); + assertThat(stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11"))) + .isEqualTo(before); + + var nextRequest = withRequestId(request, "join-request-2"); + var joined = stub.joinPublicProductionMembership(nextRequest); + assertThat(joined.getSuccess()).isTrue(); + assertThat(joined.getOutcomeCode()).isEqualTo("JOINED"); + assertThat(joined.getReplayed()).isFalse(); + assertThat(joined.getMembershipVersion()).isEqualTo(previousVersion + 1L); + assertThat(joined.getGameplayAdmissionAllowed()).isTrue(); + var after = stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); + assertThat(after.getMembershipVersion()).isEqualTo(joined.getMembershipVersion()); + assertThat(after.getMembershipLifecycleState()).isEqualTo("ACTIVE"); + + server.setAllowPublicJoin(false); + var repeated = stub.joinPublicProductionMembership(nextRequest); + assertThat(repeated).isEqualTo(joined.toBuilder().setReplayed(true).build()); + assertThat(stub.joinPublicProductionMembership(request)) + .isEqualTo(denied.toBuilder().setReplayed(true).build()); + var alreadyActive = + stub.joinPublicProductionMembership(withRequestId(request, "join-request-3")); + assertThat(alreadyActive.getSuccess()).isTrue(); + assertThat(alreadyActive.getOutcomeCode()).isEqualTo("ALREADY_ACTIVE"); + assertThat(alreadyActive.getReplayed()).isFalse(); + assertThat(alreadyActive.getMembershipVersion()).isEqualTo(joined.getMembershipVersion()); + assertThat(stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11"))) + .isEqualTo(after); + + server.denyGameplayAdmission(); + var nonAdmittingReplay = + joined.toBuilder().setReplayed(true).setGameplayAdmissionAllowed(false).build(); + assertThat(stub.joinPublicProductionMembership(nextRequest)).isEqualTo(nonAdmittingReplay); + server.allowGameplayAdmission(); + server.setMembershipInactive(); + assertThat(stub.joinPublicProductionMembership(nextRequest)).isEqualTo(nonAdmittingReplay); + assertThat(stub.joinPublicProductionMembership(request)) + .isEqualTo(denied.toBuilder().setReplayed(true).build()); + } finally { + channel.shutdownNow(); + } + } + } + + @Test + void retainedJoinRejectsConflictingCallerAndScopeIdentity() throws Exception { + try (var server = new AccountRuntimeStubServer(0)) { + server.mapAccountId("demo@example.com", 7L); + server.mapAccountId("other@example.com", 9L); + String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); + var scopeRequest = validConnectScopeRequest(accountUuid); + var channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + var request = + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(scopeRequest.getPlayerContext()) + .setConnectScopeId( + stub.issueDirectTextConnectScope(scopeRequest).getConnectScopeId()) + .setRequestId("join-request-1") + .build(); + var original = stub.joinPublicProductionMembership(request); + assertThat(original.getSuccess()).isTrue(); + var otherAccountScope = + validConnectScopeRequest(AccountRuntimeStubServer.accountUuidForTestFixture(9L)); + var otherTenantScope = + scopeRequest.toBuilder() + .setTenantId("024c8a59-d3ee-4f64-8276-c4c43a2efe7f") + .setPlayerContext( + scopeRequest.getPlayerContext().toBuilder() + .setTenantId("024c8a59-d3ee-4f64-8276-c4c43a2efe7f")) + .build(); + var sameScopeNewId = stub.issueDirectTextConnectScope(scopeRequest).getConnectScopeId(); + var conflicts = + List.of( + request.toBuilder() + .setPlayerContext(request.getPlayerContext().toBuilder().setSessionId("2")) + .build(), + request.toBuilder().setConnectScopeId(sameScopeNewId).build(), + request.toBuilder() + .setPlayerContext(otherAccountScope.getPlayerContext()) + .setConnectScopeId( + stub.issueDirectTextConnectScope(otherAccountScope).getConnectScopeId()) + .build(), + request.toBuilder() + .setPlayerContext(otherTenantScope.getPlayerContext()) + .setConnectScopeId( + stub.issueDirectTextConnectScope(otherTenantScope).getConnectScopeId()) + .build()); + + for (var conflict : conflicts) { + var rejected = stub.joinPublicProductionMembership(conflict); + assertThat(rejected.getError().getCode()).isEqualTo("IDEMPOTENCY_CONFLICT"); + assertThat(rejected.getSuccess()).isFalse(); + assertThat(rejected.getReplayed()).isFalse(); + assertThat(rejected.getAccountId()).isEmpty(); + assertThat(rejected.getTenantId()).isEmpty(); + } + assertThat(stub.joinPublicProductionMembership(request)) + .isEqualTo(original.toBuilder().setReplayed(true).build()); + } finally { + channel.shutdownNow(); + } + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void alreadyActiveNonAdmittingJoinReturnsMembershipReceiptWithoutGrantingAdmission( + boolean allowPublicJoin) throws Exception { + try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + server.mapAccountId("demo@example.com", 7L); + server.denyGameplayAdmission(); + server.setAllowPublicJoin(allowPublicJoin); + String accountUuid = AccountRuntimeStubServer.accountUuidForTestFixture(7L); + var scopeRequest = validConnectScopeRequest(accountUuid); + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + AccountServiceGrpc.AccountServiceBlockingStub stub = + AccountServiceGrpc.newBlockingStub(channel); + String connectScopeId = stub.issueDirectTextConnectScope(scopeRequest).getConnectScopeId(); + var before = stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); + var reply = + stub.joinPublicProductionMembership( + JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(scopeRequest.getPlayerContext()) + .setConnectScopeId(connectScopeId) + .setRequestId("join-request-1") + .build()); + + assertThat(reply.getSuccess()).isTrue(); + assertThat(reply.getOutcomeCode()).isEqualTo("ALREADY_ACTIVE"); + assertThat(reply.getGameplayAdmissionAllowed()).isFalse(); + assertThat(reply.getMembershipVersion()).isEqualTo(before.getMembershipVersion()); + assertThat(reply.getMembershipAuthorityGeneration()) + .isEqualTo(before.getMembershipAuthorityGeneration()); + assertThat(reply.getMembershipId()).matches("[1-9][0-9]{0,18}"); + var after = stub.getTenantMembershipForRuntime(membershipRequest(accountUuid, "11")); + assertThat(after.getMembershipExists()).isEqualTo(before.getMembershipExists()); + assertThat(after.getGameplayAdmissionAllowed()) + .isEqualTo(before.getGameplayAdmissionAllowed()); + assertThat(after.getMembershipVersion()).isEqualTo(before.getMembershipVersion()); + assertThat(after.getMembershipAuthorityGeneration()) + .isEqualTo(before.getMembershipAuthorityGeneration()); + } finally { + channel.shutdownNow(); + } + } + } + private static IssueDirectTextConnectScopeRequest validConnectScopeRequest(String accountUuid) { PlayerExecutionContext caller = PlayerExecutionContext.newBuilder() .setAccountId(accountUuid) - .setTenantId("11") + .setTenantId(TENANT_ID) .setRealmId(REALM_ID) - .setGameInstanceId("33") - .setSessionId("session-1") + .setGameInstanceId(GAME_INSTANCE_ID) + .setSessionId("1") .setPlayableStateNamespaceId(NAMESPACE_ID) .setPlayableStateScope("SHARED") .setRequestId("join-request-1") .build(); return IssueDirectTextConnectScopeRequest.newBuilder() .setPlayerContext(caller) - .setTenantId("11") + .setTenantId(TENANT_ID) .setWorldSlug("demo") .setRealmSlug("live") .setRealmId(REALM_ID) .setPlayableStateNamespaceId(NAMESPACE_ID) .setPlayableStateScope("SHARED") - .setGameInstanceId("33") + .setGameInstanceId(GAME_INSTANCE_ID) .setCatalogRevision(1L) .setPointerVersion(1L) .build(); } + private static JoinPublicProductionMembershipRequest withRequestId( + JoinPublicProductionMembershipRequest request, String requestId) { + return request.toBuilder() + .setRequestId(requestId) + .setPlayerContext(request.getPlayerContext().toBuilder().setRequestId(requestId)) + .build(); + } + private static void assertField( Descriptor descriptor, String name, int number, FieldDescriptor.Type type) { FieldDescriptor field = descriptor.findFieldByName(name); diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index 7a132094fa..4a80b18323 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -41,7 +41,9 @@ import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; -/** Shared fake Account runtime authority for cross-service gameplay tests. */ +/** + * Shared test-only Account runtime fake; its responses establish no canonical runtime authority. + */ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountServiceImplBase implements AutoCloseable { private static final Set IMPLEMENTED_RUNTIME_METHODS = @@ -70,6 +72,7 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe private final Map accountIdsByUuid = new ConcurrentHashMap<>(); private final Map profilesByAccountId = new ConcurrentHashMap<>(); private final Map connectScopesById = new ConcurrentHashMap<>(); + private final Map joinOutcomesByRequestId = new ConcurrentHashMap<>(); public AccountRuntimeStubServer(int port) throws IOException { this(port, Clock.systemUTC()); @@ -166,7 +169,7 @@ public void setRealmAccessGranted(boolean granted) { realmAccessGranted.set(granted); } - public void resetRuntimeState() { + public synchronized void resetRuntimeState() { authenticateRequests.clear(); membershipLifecycleState.set("ACTIVE"); gameplayAdmissionAllowed.set(true); @@ -181,6 +184,7 @@ public void resetRuntimeState() { .values() .forEach(id -> accountIdsByUuid.put(accountUuidForTestFixture(id), id)); connectScopesById.clear(); + joinOutcomesByRequestId.clear(); } @Override @@ -265,27 +269,11 @@ public void issueDirectTextConnectScope( IssueDirectTextConnectScopeRequest request, StreamObserver responseObserver) { PlayerExecutionContext caller = request.getPlayerContext(); - if (caller.getAccountId().isBlank() - || resolveRegisteredAccountId(caller.getAccountId()) == null - || caller.getTenantId().isBlank() - || caller.getRealmId().isBlank() - || caller.getRequestId().isBlank() - || caller.getGameInstanceId().isBlank() - || caller.getPlayableStateNamespaceId().isBlank() - || caller.getPlayableStateScope().isBlank() - || request.getTenantId().isBlank() - || request.getRealmId().isBlank() - || request.getGameInstanceId().isBlank() - || request.getWorldSlug().isBlank() - || request.getRealmSlug().isBlank() - || request.getPlayableStateNamespaceId().isBlank() - || request.getPlayableStateScope().isBlank() + if (!isValidDirectTextCaller(caller) + || !isBoundedText(request.getWorldSlug(), 128) + || !isBoundedText(request.getRealmSlug(), 128) || request.getCatalogRevision() <= 0 || request.getPointerVersion() <= 0 - || !isCanonicalUuid(caller.getRealmId()) - || !isCanonicalUuid(request.getRealmId()) - || !isCanonicalUuid(caller.getPlayableStateNamespaceId()) - || !isCanonicalUuid(request.getPlayableStateNamespaceId()) || !caller.getTenantId().equals(request.getTenantId()) || !caller.getRealmId().equals(request.getRealmId()) || !caller.getGameInstanceId().equals(request.getGameInstanceId()) @@ -327,25 +315,49 @@ private static boolean isCanonicalUuid(String value) { return false; } try { - return UUID.fromString(value).toString().equals(value); + UUID parsed = UUID.fromString(value); + return !parsed.equals(new UUID(0L, 0L)) && parsed.toString().equals(value); } catch (IllegalArgumentException ex) { return false; } } + private boolean isValidDirectTextCaller(PlayerExecutionContext caller) { + return resolveRegisteredAccountId(caller.getAccountId()) != null + && isCanonicalUuid(caller.getTenantId()) + && isCanonicalUuid(caller.getRealmId()) + && isCanonicalUuid(caller.getGameInstanceId()) + && isCanonicalUuid(caller.getPlayableStateNamespaceId()) + && Set.of("SHARED", "ISOLATED").contains(caller.getPlayableStateScope()) + && isPositiveTransportSession(caller.getSessionId()) + && isBoundedText(caller.getRequestId(), 128); + } + + private static boolean isPositiveTransportSession(String value) { + if (value.length() > 32 || !value.matches("[0-9]+")) { + return false; + } + try { + return Long.parseLong(value) > 0; + } catch (NumberFormatException ex) { + return false; + } + } + + private static boolean isBoundedText(String value, int maximumLength) { + return !value.isBlank() && value.length() <= maximumLength; + } + @Override - public void joinPublicProductionMembership( + public synchronized void joinPublicProductionMembership( JoinPublicProductionMembershipRequest request, StreamObserver responseObserver) { PlayerExecutionContext caller = request.getPlayerContext(); StubConnectScope scope = connectScopesById.get(request.getConnectScopeId()); - if (request.getConnectScopeId().isBlank() - || request.getRequestId().isBlank() + if (!isBoundedText(request.getConnectScopeId(), 2048) + || !isBoundedText(request.getRequestId(), 128) || !request.getRequestId().equals(caller.getRequestId()) - || caller.getAccountId().isBlank() - || resolveRegisteredAccountId(caller.getAccountId()) == null - || caller.getTenantId().isBlank() - || caller.getSessionId().isBlank() + || !isValidDirectTextCaller(caller) || scope == null || !scope.expiresAt().isAfter(clock.instant()) || !scope.accountId().equals(caller.getAccountId()) @@ -361,29 +373,68 @@ public void joinPublicProductionMembership( .setCode("INVALID_ARGUMENT") .setMessage("Direct-text JOIN request is incomplete")) .build()); + } else { + StubJoinOutcome retained = joinOutcomesByRequestId.get(request.getRequestId()); + if (retained != null) { + if (retained.request().equals(request)) { + var replay = retained.response().toBuilder().setReplayed(true); + if (retained.response().getSuccess()) { + // A retained membership receipt never preserves historical admission permission. + replay.setGameplayAdmissionAllowed( + "ACTIVE".equals(membershipLifecycleState.get()) && gameplayAdmissionAllowed.get()); + } + responseObserver.onNext(replay.build()); + } else { + responseObserver.onNext( + JoinPublicProductionMembershipResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("IDEMPOTENCY_CONFLICT") + .setMessage("Direct-text JOIN request ID conflicts")) + .build()); + } + } else { + JoinPublicProductionMembershipResponse response = evaluateJoin(caller); + joinOutcomesByRequestId.put(request.getRequestId(), new StubJoinOutcome(request, response)); + responseObserver.onNext(response); + } + } + responseObserver.onCompleted(); + } + + private JoinPublicProductionMembershipResponse evaluateJoin(PlayerExecutionContext caller) { + if ("ACTIVE".equals(membershipLifecycleState.get())) { + return JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(true) + .setOutcomeCode("ALREADY_ACTIVE") + .setAccountId(caller.getAccountId()) + .setTenantId(caller.getTenantId()) + .setMembershipId("1") + .setMembershipVersion(membershipVersion.get()) + .setMembershipAuthorityGeneration(membershipAuthorityGeneration.get()) + .setGameplayAdmissionAllowed(gameplayAdmissionAllowed.get()) + .build(); } else if (!allowPublicJoin.get()) { - responseObserver.onNext( - JoinPublicProductionMembershipResponse.newBuilder() - .setOutcomeCode("PUBLIC_PRODUCTION_ADMISSION_DENIED") - .setAccountId(caller.getAccountId()) - .setTenantId(caller.getTenantId()) - .build()); + return JoinPublicProductionMembershipResponse.newBuilder() + .setOutcomeCode("PUBLIC_PRODUCTION_ADMISSION_DENIED") + .setAccountId(caller.getAccountId()) + .setTenantId(caller.getTenantId()) + .build(); } else { + long joinedMembershipVersion = membershipVersion.incrementAndGet(); membershipLifecycleState.set("ACTIVE"); gameplayAdmissionAllowed.set(true); - responseObserver.onNext( - JoinPublicProductionMembershipResponse.newBuilder() - .setSuccess(true) - .setOutcomeCode("JOINED") - .setAccountId(caller.getAccountId()) - .setTenantId(caller.getTenantId()) - .setMembershipId( - "stub-membership-" + caller.getAccountId() + "-" + caller.getTenantId()) - .setMembershipVersion(1L) - .setMembershipAuthorityGeneration(1L) - .build()); + return JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(true) + .setOutcomeCode("JOINED") + .setAccountId(caller.getAccountId()) + .setTenantId(caller.getTenantId()) + .setMembershipId("1") + .setMembershipVersion(joinedMembershipVersion) + .setMembershipAuthorityGeneration(membershipAuthorityGeneration.get()) + .setGameplayAdmissionAllowed(true) + .build(); } - responseObserver.onCompleted(); } @Override @@ -487,4 +538,8 @@ private record StubConnectScope( String playableStateNamespaceId, String playableStateScope, Instant expiresAt) {} + + private record StubJoinOutcome( + JoinPublicProductionMembershipRequest request, + JoinPublicProductionMembershipResponse response) {} } diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index bf74dc929e..7f4e0d1c26 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -7,6 +7,7 @@ import com.google.protobuf.Empty; import com.google.protobuf.util.JsonFormat; +import com.zaxxer.hikari.HikariDataSource; import integration.net.firedevops.firemud.gamesession.repository.CanonicalHumanPublicationOwnerTestFixtures; import io.grpc.BindableService; import io.grpc.CallOptions; @@ -304,7 +305,9 @@ class WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest { @Container static final PostgreSQLContainer ACCOUNT = - new PostgreSQLContainer<>(TestContainerImages.postgres()); + // Account's exact-original LOGIN disposal refuses nondurable PostgreSQL settings. + new PostgreSQLContainer<>(TestContainerImages.postgres()) + .withCommand("postgres", "-c", "fsync=on", "-c", "synchronous_commit=on"); @Container static final GenericContainer REDIS = @@ -583,6 +586,9 @@ private void compose( "Created placement proof requires the committed coupled owner path"); } UUID tenant = UUID.randomUUID(); + var sharedAuthoredSource = controlledSource("controlled-upstream", tenant); + var sharedCreation = + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(sharedAuthoredSource); try (var account = new AccountControlUiOriginalOrderFixture( ACCOUNT.getJdbcUrl(), @@ -591,12 +597,22 @@ private void compose( REDIS.getHost(), REDIS.getMappedPort(6379), proofDirectory.resolve("account"), - tenant); + sharedCreation, + true); var world = database(WORLD, "world-management-service", true); var gs = database(GS, "game-session-service", true)) { var issuer = new AccountOriginalStartSessionAuthorizationProofFixture( account, proofDirectory.resolve("issuer"), NAMESPACE); + var accountDurability = + issuer + .sourceDsl() + .fetchSingle( + "SELECT pg_is_in_recovery() AS recovery, current_setting('fsync') AS fsync," + + " current_setting('synchronous_commit') AS commit_mode"); + assertThat(accountDurability.get("recovery", Boolean.class)).isFalse(); + assertThat(accountDurability.get("fsync", String.class)).isEqualTo("on"); + assertThat(accountDurability.get("commit_mode", String.class)).isEqualTo("on"); Duration lease = refusal == Refusal.EXPIRED_ATTEMPT ? Duration.ofSeconds(30) @@ -680,7 +696,14 @@ public void attachAccountRedemptionProjection( var createdPublication = new AtomicReference(); var preparedInput = preparationInputs( - world, gs, tuple, claim.get(), tenant, playerCreatedPlacement, createdPublication); + world, + gs, + tuple, + claim.get(), + tenant, + playerCreatedPlacement, + createdPublication, + sharedAuthoredSource); var input = refusal == Refusal.MISMATCHED_ATTEMPT ? new WorldCanonicalInstancePreparation.Input( @@ -1858,6 +1881,7 @@ public void close() {} exerciseCoupledCanonicalInitialAdmission( gs, world, + account, issuer, currentAttempt, proofDirectory, @@ -2336,7 +2360,9 @@ private static javax.sql.DataSource dataSource(DSLContext dsl) { var provider = (org.jooq.impl.DataSourceConnectionProvider) dsl.configuration().connectionProvider(); var proxy = (TransactionAwareDataSourceProxy) provider.dataSource(); - return Objects.requireNonNull(proxy.getTargetDataSource()); + var target = Objects.requireNonNull(proxy.getTargetDataSource()); + // Concurrency/fence probes retain independent physical connections outside the owner pool. + return target instanceof HikariDataSource pool ? pool.getDataSource() : target; } private static SQLException findSqlException(Throwable failure) { @@ -2422,6 +2448,7 @@ private static String prefixedSha256(byte[] bytes) { private static void exerciseCoupledCanonicalInitialAdmission( Database gs, Database world, + AccountControlUiOriginalOrderFixture account, AccountOriginalStartSessionAuthorizationProofFixture issuer, GrpcOriginalStartSessionCurrentAttemptClient currentAttempt, Path proofDirectory, @@ -3004,6 +3031,7 @@ private static void exerciseCoupledCanonicalInitialAdmission( composeActualEntityWorldRegionPrerequisite( gs, world, + account, proofDirectory, pki, factory, @@ -3084,6 +3112,7 @@ private static void assertAccountAdmissionProtectionSettled( private static void composeActualEntityWorldRegionPrerequisite( Database gs, Database world, + AccountControlUiOriginalOrderFixture account, Path proofDirectory, WorldOriginalStartSessionPreparationProofPki worldPki, GrpcChannelFactory channels, @@ -3432,6 +3461,8 @@ private static void composeActualEntityWorldRegionPrerequisite( try { var worldEndpoints = new ServiceEndpointsProperties(); worldEndpoints.setWorldManagementService("127.0.0.1:" + worldLocationServer.getPort()); + // The earlier generic password-write proof deliberately leaves creator LOGIN + // currentness unavailable. The later composition uses a separate fresh player. var initialLocationClient = new CanonicalInitialPlayerLocationClient( worldEndpoints, worldPki.client("game-session-service"), channels, NAMESPACE); @@ -3538,6 +3569,18 @@ private static void composeActualEntityWorldRegionPrerequisite( assertThat(regionProofs.foreignOwnerCapabilityRejectedWithoutStateChange()).isTrue(); assertThat(regionProofs.expiredGrantRejectedWithoutStateChange()).isTrue(); } + // Run the genuine second-player DEMO mutation after original placement assertions. + WorldPublishedAdmissionSourceComposition.exercise( + proofDirectory, + gs.dsl(), + gs.manager(), + REDIS.getHost(), + REDIS.getMappedPort(6379), + currentTarget, + accountUuid, + account, + worldEndpoints, + worldPki.client("game-session-service")); } finally { shutdown(worldLocationServer); entityReceiptClient.close(); @@ -4157,11 +4200,11 @@ private static WorldCanonicalInstancePreparation.Input preparationInputs( GameSessionStartSessionOperatorAttemptRepository.AttemptClaim claim, UUID tenant, boolean playerCreatedPlacement, - AtomicReference createdPublication) + AtomicReference createdPublication, + AuthoredWorldSourceEvidence source) throws Exception { var intakeRepository = new WorldAuthoredSourceIntakeRepository(world.dsl()); var versionRepository = new WorldAuthoredVersionIdentityRepository(world.dsl()); - var source = controlledSource("controlled-upstream", tenant); var intake = Objects.requireNonNull( world @@ -4771,47 +4814,73 @@ private static Database database(PostgreSQLContainer postgres, String service .getConfigurationExtension(PostgreSQLConfigurationExtension.class) .setTransactionalLock(false); } - migrations.load().migrate(); - var manager = new DataSourceTransactionManager(source); - var write = new TransactionTemplate(manager); - write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); - WorldRuntimeInstallationRegistry installation = null; - if ("world-management-service".equals(service)) { - // This is a stipulated one-workload installation solely for this receiving-owner proof. - // Real Account/GS/mTLS behavior remains exercised independently; none supplies global - // installed membership, deployment completeness or production source custody. - byte[] artifact = controlledInstallationArtifact(schema); - installation = - new WorldRuntimeInstallationRegistry( - dsl, - manager, - schema, - NAMESPACE, - () -> - new WorldRuntimeInstallationRegistry.HeldInstallation() { - private boolean closed; + HikariDataSource pool = null; + try { + migrations.load().migrate(); + if ("world-management-service".equals(service) || "game-session-service".equals(service)) { + pool = new HikariDataSource(); + pool.setPoolName("world-fixture-" + schema); + pool.setDataSource(source); + pool.setMaximumPoolSize(4); + pool.setMinimumIdle(0); + } + javax.sql.DataSource ownerSource = pool == null ? source : pool; + var manager = new DataSourceTransactionManager(ownerSource); + var write = new TransactionTemplate(manager); + write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(ownerSource), SQLDialect.POSTGRES); + WorldRuntimeInstallationRegistry installation = null; + if ("world-management-service".equals(service)) { + // This is a stipulated one-workload installation solely for this receiving-owner proof. + // Real Account/GS/mTLS behavior remains exercised independently; none supplies global + // installed membership, deployment completeness or production source custody. + byte[] artifact = controlledInstallationArtifact(schema); + installation = + new WorldRuntimeInstallationRegistry( + dsl, + manager, + schema, + NAMESPACE, + () -> + new WorldRuntimeInstallationRegistry.HeldInstallation() { + private boolean closed; - @Override - public byte[] exactArtifactBytes() { - return artifact.clone(); - } + @Override + public byte[] exactArtifactBytes() { + return artifact.clone(); + } - @Override - public void requireCurrent() { - if (closed) - throw new IllegalStateException("Synthetic installation hold is closed"); - } + @Override + public void requireCurrent() { + if (closed) + throw new IllegalStateException("Synthetic installation hold is closed"); + } - @Override - public void close() { - closed = true; - } - }); - installation.register(); + @Override + public void close() { + closed = true; + } + }); + installation.register(); + } + return new Database(schema, dsl, manager, write, installation, pool); + } catch (RuntimeException | Error failure) { + try { + DSL.using(source, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } catch (RuntimeException | Error cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + if (pool != null) { + try { + pool.close(); + } catch (RuntimeException | Error cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + } + throw failure; } - return new Database(schema, dsl, manager, write, installation); } private static WorldRuntimeInstallationRegistry.Registration advanceInstallationRegistry( @@ -4911,11 +4980,14 @@ private record Database( DSLContext dsl, DataSourceTransactionManager manager, TransactionTemplate write, - WorldRuntimeInstallationRegistry installationRegistry) + WorldRuntimeInstallationRegistry installationRegistry, + HikariDataSource pool) implements AutoCloseable { @Override public void close() { - dsl.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + try (HikariDataSource ownedPool = pool) { + dsl.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } } } diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java new file mode 100644 index 0000000000..893cfbbd9d --- /dev/null +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java @@ -0,0 +1,263 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.util.UUID; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerAdmissionSharedEntitlementFixture; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; +import net.firedevops.firemud.gamesession.client.DirectTextIssuedConnectScope; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginPhysicalCompositionFixture; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; + +/** + * Actual LOGIN and PLAYER_ADMISSION producer/consumer with a genuine absent player and shared + * Account/GS/World sources and physical GS journal/PENDING/INSTALLED state, followed by actual + * first JOIN, positive source read and known-token retirement. DEMO policy, caller coordinates, + * PKI, reset/promotion qualification and receiving custody remain controlled. No public ingress, + * protected receiving custody, World hold across JOIN, runtime activation or PLAY is proved. + */ +final class WorldPlayerAdmissionEntitlementComposition { + private WorldPlayerAdmissionEntitlementComposition() {} + + static void exercise( + Path root, + AccountControlUiOriginalOrderFixture original, + CanonicalGameplayAdmissionDecisionReadClient targets, + CanonicalPlayableTarget target, + org.jooq.DSLContext gs, + org.springframework.transaction.PlatformTransactionManager gsTransactions, + String redisHost, + int redisPort) + throws Exception { + var clock = Clock.systemUTC(); + String namespace = target.targetNamespace(); + Path directory = Files.createDirectories(root.resolve("player-admission")); + var pki = + LoopbackMtlsTestPki.create( + directory, + "Controlled genuine player admission sources", + new LoopbackMtlsTestPki.IdentitySpec( + "gs", "spiffe://firemud/ns/" + namespace + "/sa/game-session-service", false), + new LoopbackMtlsTestPki.IdentitySpec( + "account", "spiffe://firemud/ns/" + namespace + "/sa/account-service", true)); + var creation = original.creationEvidence(); + var demo = + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + creation.canonicalTenantId(), + creation.creationRequestId(), + creation.requestDigest(), + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3, 2, 4096)); + var fixture = + new AccountPlayerAdmissionSharedEntitlementFixture( + original, directory, targets, demo, clock); + var loginOwner = fixture.login(); + var keys = pki.keyManagerFactory(pki.identity("account")); + var trust = pki.trustManagerFactory(); + Server loginServer = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder.forServer(keys)) + .trustManager(trust) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + loginOwner.authenticateReceiver(namespace), new GrpcPeerIdentityInterceptor())) + .build() + .start(); + try (var loginLifetime = WorldPublishedAdmissionSourceComposition.stopOnClose(loginServer)) { + Server entitlementServer = + fixture.receiver().createUnregisteredServer("127.0.0.1:0", keys, trust); + entitlementServer.start(); + try (var entitlementLifetime = + WorldPublishedAdmissionSourceComposition.stopOnClose(entitlementServer)) { + var loginEndpoints = new ServiceEndpointsProperties(); + loginEndpoints.setAccountService("localhost:" + loginServer.getPort()); + var entitlementEndpoints = new ServiceEndpointsProperties(); + entitlementEndpoints.setAccountService("localhost:" + entitlementServer.getPort()); + var tls = pki.clientProperties(directory, pki.identity("gs")); + var channels = new GrpcChannelFactory(); + var source = fixture.trustedJwksSource(); + var verifier = + new AccountAsymmetricJwtVerifier( + new AccountPublicJwksCache( + source, source.sourceIdentity(), clock, Duration.ofSeconds(30)), + clock); + try (var loginClient = + new CanonicalGameplayLoginAccountClient( + loginEndpoints, + tls, + channels, + BlockingGrpcStubCustomizer.noop(), + namespace, + clock, + Duration.ofSeconds(15), + verifier); + var entitlementClient = + new AccountPlayerAdmissionEntitlementClient( + entitlementEndpoints, tls, channels, namespace, clock)) { + loginClient.initialize(); + entitlementClient.init(); + // This request is only a controlled credential source. GS allocates real coordinates. + var credentialSource = + loginOwner.loginRequest( + UUID.randomUUID(), + new GameplayCredentialSourceContext( + UUID.randomUUID(), "192.0.2.42", "trusted_tcp_proxy")); + try (var physicalLogin = + InitialGameplayLoginPhysicalCompositionFixture.open( + gs, + gsTransactions, + redisHost, + redisPort, + loginClient, + credentialSource.email(), + "192.0.2.42", + credentialSource.credential().toCharArray())) { + var login = physicalLogin.loginResult(); + var evidence = login.evidence(); + loginOwner.assertCommittedNonAdmittingLogin( + evidence.requestId(), + evidence.callerContextId(), + evidence.tokenJti(), + evidence.tokenSha256(), + evidence.expiresAtEpochSecond()); + var transport = new ObservedDirectTextTransport("1", UUID.randomUUID()); + var realmScope = + fixture.issueScopeWithControlledGameSessionCaller( + new DirectTextCallerContext( + evidence.accountId(), + target.canonicalTenantId(), + target.realmId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + transport.transportSessionId(), + UUID.randomUUID().toString()), + new DirectTextJoinTarget( + target.canonicalTenantId(), + target.realmId(), + target.worldSlug(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion())); + var scope = realmScope.scope(); + var issued = + DirectTextIssuedConnectScope.fromAccountResponse( + evidence.accountId().toString(), + DirectTextAuthenticatedLobbyScope.targetFor(target), + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId(scope.connectScopeId()) + .setEvaluatedAt(scope.evaluatedAt()) + .setConnectScopeExpiresAt(scope.connectScopeExpiresAt()) + .build(), + clock); + var coordinates = physicalLogin.coordinates(); + // Physical INSTALLED readback is real; protected receiving custody remains controlled. + var lobby = + new DirectTextAuthenticatedLobbyScope( + UUID.randomUUID(), + physicalLogin.installedReadback(), + transport, + target, + issued); + var received = + entitlementClient.read( + lobby, coordinates, transport, UUID.randomUUID(), login, () -> true); + fixture.assertNonAdmittingEvidence(received); + assertThat(received.fields()).containsEntry("variant", "PLAYER_ADMISSION"); + // Actual Account owner transition; caller binding is controlled and no World hold + // spans this JOIN transaction. Reuse only the still-current verified LOGIN result. + fixture.commitFirstJoin( + realmScope, UUID.randomUUID().toString(), transport.transportSessionId()); + var joined = + entitlementClient.read( + lobby, coordinates, transport, UUID.randomUUID(), login, () -> true); + fixture.assertAdmittingEvidence(joined); + var journal = new InitialGameplayLoginCoordinationJournalRepository(gs); + var beforeCustodyRefusal = journal.readCommitted(coordinates).orElseThrow(); + assertThatThrownBy( + () -> + entitlementClient.read( + lobby, coordinates, transport, UUID.randomUUID(), login, () -> false)) + .isExactlyInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + var status = ((StatusRuntimeException) failure).getStatus(); + assertThat(status.getCode()).isEqualTo(Status.Code.CANCELLED); + assertThat(status.getDescription()) + .isEqualTo("Account player-admission entitlement read did not complete"); + }); + fixture.assertAdmittingEvidence(joined); + assertThat(login.evidence()).isEqualTo(evidence); + assertThat(journal.readCommitted(coordinates)).contains(beforeCustodyRefusal); + assertThat(physicalLogin.abandonOriginalAfterCustodyLoss().status()) + .isEqualTo( + net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwner + .Status.ACCOUNT_RETIRED); + var beforeClosedResultRefusal = journal.readCommitted(coordinates).orElseThrow(); + // Cleanup has closed the private result. This proves local disposal refusal, + // not an Account-side retired-token read over the wire. + assertThatThrownBy( + () -> + entitlementClient.read( + lobby, coordinates, transport, UUID.randomUUID(), login, () -> true)) + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage("Canonical LOGIN private result is closed"); + fixture.assertAdmittingEvidence(joined); + assertThat(login.evidence()).isEqualTo(evidence); + assertThat(journal.readCommitted(coordinates)).contains(beforeClosedResultRefusal); + } catch (RuntimeException | Error failure) { + failure.addSuppressed( + new AssertionError( + "Account LOGIN owner stages: " + loginOwner.ownerObservations())); + throw failure; + } + } + } + } + } +} diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceCleanupTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceCleanupTest.java new file mode 100644 index 0000000000..836920793e --- /dev/null +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceCleanupTest.java @@ -0,0 +1,112 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Server; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; + +class WorldPublishedAdmissionSourceCleanupTest { + @Test + void successfulBodyStopsServerAndChecksLatePeerDiagnostic() throws Exception { + var server = stoppedServer(); + var peer = new AtomicReference(); + Throwable result = + catchThrowable( + () -> { + try (var peerCheck = WorldPublishedAdmissionSourceComposition.checkPeerOnClose(peer); + var lifetime = WorldPublishedAdmissionSourceComposition.stopOnClose(server)) { + peer.set("wrong authenticated peer"); + } + }); + + assertThat(result) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("wrong authenticated peer"); + verify(server).shutdownNow(); + verify(server).awaitTermination(5, TimeUnit.SECONDS); + } + + @Test + void primaryFailureRetainsPeerDiagnostic() throws Exception { + var server = stoppedServer(); + var primary = new AssertionError("admission failed"); + Throwable result = run(server, "wrong authenticated peer", primary); + + assertThat(result).isSameAs(primary); + assertThat(result.getSuppressed()).hasSize(1); + assertThat(result.getSuppressed()[0]) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("published policy source peer") + .hasMessageContaining("wrong authenticated peer"); + } + + @Test + void primaryFailureRetainsCleanupFailureAndPeerDiagnostic() throws Exception { + var server = stoppedServer(); + var cleanup = new InterruptedException("cleanup interrupted"); + when(server.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(cleanup); + var primary = new AssertionError("admission failed"); + Throwable result = run(server, "wrong authenticated peer", primary); + + assertThat(result).isSameAs(primary); + assertThat(result.getSuppressed()).hasSize(2); + assertThat(result.getSuppressed()[0]).isSameAs(cleanup); + assertThat(result.getSuppressed()[1]).hasMessageContaining("wrong authenticated peer"); + } + + @Test + void cleanupFailureRemainsPrimaryWhenBodySucceeds() throws Exception { + var server = stoppedServer(); + var cleanup = new IllegalStateException("shutdown failed"); + when(server.shutdownNow()).thenThrow(cleanup); + Throwable result = run(server, "wrong authenticated peer", null); + + assertThat(result).isSameAs(cleanup); + assertThat(result.getSuppressed()).hasSize(1); + assertThat(result.getSuppressed()[0]).hasMessageContaining("wrong authenticated peer"); + } + + @Test + void unsuccessfulTerminationCannotReplacePrimaryFailure() throws Exception { + var server = stoppedServer(); + when(server.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(false); + var primary = new AssertionError("admission failed"); + Throwable result = run(server, null, primary); + + assertThat(result).isSameAs(primary); + assertThat(result.getSuppressed()).singleElement().isInstanceOf(AssertionError.class); + } + + @Test + void successfulBodyAndCleanupDoNotFail() throws Exception { + var server = stoppedServer(); + assertThat(run(server, null, null)).isNull(); + verify(server).shutdownNow(); + verify(server).awaitTermination(5, TimeUnit.SECONDS); + } + + private static Server stoppedServer() throws InterruptedException { + var server = mock(Server.class); + when(server.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + return server; + } + + private static Throwable run(Server server, String peerFailure, AssertionError primary) { + var peer = new AtomicReference<>(peerFailure); + return catchThrowable( + () -> { + try (var peerCheck = WorldPublishedAdmissionSourceComposition.checkPeerOnClose(peer); + var lifetime = WorldPublishedAdmissionSourceComposition.stopOnClose(server)) { + if (primary != null) { + throw primary; + } + } + }); + } +} diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java new file mode 100644 index 0000000000..6d66e9b778 --- /dev/null +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java @@ -0,0 +1,273 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.BindableService; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.repository.CanonicalPublishedAdmissionActualOwnerCompositionFixture; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.jooq.DSLContext; + +/** + * Real GS OPEN/current publication and World ACTIVE reads over authenticated sockets, followed by + * actual Account LOGIN, absent-player entitlement, owner-local first JOIN and positive source + * reread. Game Design publication, DEMO policy, PKI, caller coordinates and custody callbacks are + * controlled. No public ingress, World hold across JOIN, protected receiving custody or activation + * is proved. + */ +final class WorldPublishedAdmissionSourceComposition { + private WorldPublishedAdmissionSourceComposition() {} + + static void exercise( + Path root, + DSLContext gs, + org.springframework.transaction.PlatformTransactionManager gsTransactions, + String redisHost, + int redisPort, + CanonicalPlayableTarget target, + UUID account, + net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture + originalAccount, + ServiceEndpointsProperties worldEndpoints, + CommonGrpcClientProperties worldTls) + throws Exception { + assertThat(target.characterCreationPolicy()).isEqualTo("PRESEEDED_ONLY"); + var publication = + RealmPolicyPublishedEvidenceCodec.decode( + gs.fetchSingle( + "SELECT complete_policy_set_evidence FROM game_session_canonical_realm_catalog WHERE realm_id=?", + target.realmId()) + .get(0, byte[].class)); + String namespace = target.targetNamespace(); + Path directory = Files.createDirectories(root.resolve("published-admission-source")); + var pki = + LoopbackMtlsTestPki.create( + directory, + "Controlled published source composition", + new LoopbackMtlsTestPki.IdentitySpec( + "gs-server", peer(namespace, "game-session-service"), true), + new LoopbackMtlsTestPki.IdentitySpec( + "gs-client", peer(namespace, "game-session-service"), false), + new LoopbackMtlsTestPki.IdentitySpec( + "account", peer(namespace, "account-service"), false), + new LoopbackMtlsTestPki.IdentitySpec( + "design", peer(namespace, "game-design-service"), true)); + var policies = + new PublishedRealmEntryPolicySetEvidence( + publication.target(), + publication.versionNumber(), + publication.sourceCommitId(), + publication.sourceEpoch(), + publication.publishedReleaseBundleRef(), + publication.publishedReleaseBundleDigest(), + publication.publishWorkflowId(), + publication.manifestHash(), + publication.publicationVersionStateEpoch(), + publication.operationBytes(), + publication.captureBytes(), + publication.terminalEvidenceBytes(), + publication.policyCount(), + publication.policySetDigest(), + publication.policies().stream() + .map( + p -> + new PublishedRealmEntryPolicyEvidence( + p.policyId(), + p.source().commitId(), + p.source().revisionId(), + p.source().logicalRevisionId(), + p.source().policy(), + p.policyDigest())) + .toList()); + // This is the sole stipulated source: the exact published set already used by the real + // preparation/OPEN owners. No Game Design issuing-owner proof is claimed here. + var policySourcePeerFailure = new AtomicReference(); + var policySource = + new PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceImplBase() { + @Override + public void listPublishedRealmEntryPolicies( + ListPublishedRealmEntryPoliciesRequest request, + StreamObserver observer) { + var authenticatedPeer = GrpcPeerIdentity.current(); + String expectedPeer = peer(namespace, "game-session-service"); + if (authenticatedPeer == null || !expectedPeer.equals(authenticatedPeer.uri())) { + policySourcePeerFailure.compareAndSet( + null, + "Expected authenticated peer " + + expectedPeer + + " but was " + + (authenticatedPeer == null ? "missing" : authenticatedPeer.uri())); + } + observer.onNext( + PublishedRealmEntryPolicyReadGrpcCodec.toResponse( + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest(request), policies)); + observer.onCompleted(); + } + }; + Server design = server(pki, "design", policySource); + // Reverse close order retains shutdown and peer diagnostics as suppressed failures. + try (var peerCheck = checkPeerOnClose(policySourcePeerFailure); + var designLifetime = stopOnClose(design)) { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + design.getPort()); + var channels = new GrpcChannelFactory(); + try (var policyClient = + new GameDesignPublishedRealmPolicyClient( + endpoints, + pki.clientProperties(directory, pki.identity("gs-client")), + channels, + namespace); + var worldClient = + new WorldCanonicalInstanceLifecycleClient( + worldEndpoints, worldTls, channels, namespace)) { + policyClient.init(); + worldClient.init(); + Server receiver = + server( + pki, + "gs-server", + CanonicalPublishedAdmissionActualOwnerCompositionFixture.receiver( + gs, namespace, policyClient, worldClient)); + try (var receiverLifetime = stopOnClose(receiver)) { + endpoints.setGameSessionService("localhost:" + receiver.getPort()); + try (var accountClient = + new CanonicalGameplayAdmissionDecisionReadClient( + endpoints, + pki.clientProperties(directory, pki.identity("account")), + channels, + namespace)) { + accountClient.init(); + var selector = + new RetainedTargetSelector( + UUID.randomUUID(), + account, + namespace, + target.canonicalTenantId(), + target.tenantSlug(), + target.worldSlug(), + target.realmId(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion()); + var resolved = accountClient.resolvePublishedRealmAdmissionTarget(selector); + var read = accountClient.readPublishedRealmAdmissionOwner(resolved.strictSelector()); + assertThat(read.selector()).isEqualTo(resolved.strictSelector()); + assertThat(read.currentTarget().canonicalGameInstanceId()) + .isEqualTo(target.canonicalGameInstanceId()); + assertThat(read.sourceEvidence().admissionPointerSnapshotDigest()) + .isEqualTo(target.admissionPointerSnapshotDigest()); + assertThat(read.sourceEvidence().gameSessionOwnerProof().proofDigest()) + .isEqualTo(target.ownerProofDigest()); + assertThat(read.sourceEvidence().publishedPolicySetEvidence().canonicalBytes()) + .containsExactly(policies.canonicalBytes()); + assertThat(read.worldLifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(read.worldLifecycleEvidence().lifecycleEpoch()) + .isEqualTo(target.activeWorldEpoch()); + var wrong = + new RetainedTargetSelector( + UUID.randomUUID(), + account, + namespace, + target.canonicalTenantId(), + target.tenantSlug(), + target.worldSlug(), + target.realmId(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + UUID.randomUUID(), + target.catalogRevision(), + target.pointerVersion()); + assertThatThrownBy(() -> accountClient.resolvePublishedRealmAdmissionTarget(wrong)) + .isExactlyInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + var status = ((StatusRuntimeException) failure).getStatus(); + assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status.getDescription()) + .isEqualTo("Canonical Game Session admission decision is unavailable"); + }); + var afterRefusal = accountClient.resolvePublishedRealmAdmissionTarget(selector); + assertThat(afterRefusal.selector()).isEqualTo(resolved.selector()); + assertThat(afterRefusal.currentTarget()).isEqualTo(resolved.currentTarget()); + WorldPlayerAdmissionEntitlementComposition.exercise( + root, + originalAccount, + accountClient, + target, + gs, + gsTransactions, + redisHost, + redisPort); + } + } + } + } + } + + static AutoCloseable checkPeerOnClose(AtomicReference peerFailure) { + return () -> assertThat(peerFailure.get()).as("published policy source peer").isNull(); + } + + static AutoCloseable stopOnClose(Server server) { + return () -> stop(server); + } + + private static String peer(String namespace, String service) { + return "spiffe://firemud/ns/" + namespace + "/sa/" + service; + } + + private static Server server( + LoopbackMtlsTestPki.Pki pki, String identity, BindableService receiver) throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder.forServer( + pki.keyManagerFactory(pki.identity(identity)))) + .trustManager(pki.trustManagerFactory()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(receiver, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } +}